﻿using Bandit.Helpers;
//new
using Bandit.UI;
using Bandit.UI.Controls;
using ETC.DLEDLightingSystemPlus.Core;
using ETC.DLEDLightingSystemPlus.Helpers;
using ETC.DLEDLightingSystemPlus.Models;
using ETC.DLEDLightingSystemPlus.UserControls;
using ETC.DLEDLightingSystemPlus.Windows;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Crypto.Modes.Gcm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
//using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace ETC.DLEDLightingSystemPlus
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : BanditWindow
    {
        /// <summary>
        /// 视图模型
        /// </summary>
        public ViewModels.MainViewModel ViewModel { get { return App.MainViewModel; } }

        public HoneyWell3320TCPHelper honeyWell3320TCPHelper1;

        public HoneyWell3320TCPHelper honeyWell3320TCPHelper2;

        //public HoneyWell3320Helper honeyWell3320Helper1;

        //public HoneyWell3320Helper honeyWell3320Helper2;

        public MelsecPLCHelper m_MelsecPLCHelper;

        private bool LinkPLCFrist;
        /// 是否添加操作
        /// </summary>
        protected bool IsAdding { get; set; }

        TetraController _Tetra = null;
        public MainWindow()
        {
            //让弹窗位于屏幕中心
            WindowStartupLocation = WindowStartupLocation.CenterScreen;

            InitializeComponent();

            JsonConfig.LoadJsonConfig();

            ViewModel.JsonConfig = JsonConfig.Instance;

            System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level = System.Diagnostics.SourceLevels.Critical;

            this.CurrentShowGrid = this.GridOperator;

            #region Window Loaded

            this.Loaded += delegate
            {
                ViewModel.OnClick = new Bandit.UI.MVVM.CommandHandler(OnClick);
                ViewModel.OnPLCClick = new Bandit.UI.MVVM.CommandHandler(OnPLCClick);
                this.ViewModel.OnLoginChanged += (isLogin) =>
                {
                    //columnCheck.Width = isLogin ? 40 : 0;
                };

                this.DataContext = ViewModel;

                this.rtxtPLCTestData.Document.Blocks.Clear();

                if (!ConfigHelper.GetValueToBoolean("IsPLCDebug"))
                {
                    //InitScanSerial1();
                    //InitScanSerial2();
                    //try
                    //{
                    //    Task.Factory.StartNew(() =>
                    //    {
                            InitScanTCP1();
                    //    });
                    //}
                    //catch (Exception ex)
                    //{
                    //    LogHelper.Error(ex, "MainViewModel.InitScanTCP1");
                    //}

                    //try
                    //{
                    //    Task.Factory.StartNew(() =>
                    //    {
                            InitScanTCP2();
                    //    });
                    //}
                    //catch (Exception ex)
                    //{
                    //    LogHelper.Error(ex, "MainViewModel.InitScanTCP2");
                    //}

                    try
                    {
                        this.Loading.Show("Link PLC ...");
                        Task.Factory.StartNew(() =>
                        {
#if !DEBUG

                            this.OpenPLC();

#endif

                        }).ContinueWith(t =>
                        {
                            this.Loading.Hide();
                        });
                   
                    }
                    catch(Exception ex)
                    {
                        LogHelper.Error(ex, "MainViewModel.OpenPLC");
                    }
                }
                //加载Stations
                try
                {
                    this.ViewModel.LoadStations();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex, "MainViewModel.LoadStations");
                    this.ShowDialog(ex.Message, "Error", MessageBoxButton.OK, Bandit.UI.DialogIcon.Error);
                }

                #region PG列表事件

                this.lbTetraItems.SelectionChanged += (sender, e) =>
                {
                    Refresh();

                    if (this.lbTetraItems.SelectedItems != null && this.lbTetraItems.SelectedItems.Count > 0)
                    {
                        this.ViewModel.TetraModel = this.lbTetraItems.SelectedItem as Tetra;
                    }
                    else
                    {
                        this.ViewModel.TetraModel = new Tetra();
                    }

                };

                this.lbTetraItems.MouseLeftButtonDown += (sender, e) =>
                {
                    if (e.OriginalSource.GetType().Name.Equals("ScrollViewer"))
                    {
                        this.lbTetraItems.SelectedItem = null;
                    }
                };

                this.lbTetraItems.MouseDoubleClick += (sender, e) =>
                {
                    //this.Update();
                    Refresh();

                    if (this.lbTetraItems.SelectedItems != null && this.lbTetraItems.SelectedItems.Count > 0)
                    {
                        this.ViewModel.TetraModel = this.lbTetraItems.SelectedItem as Tetra;
                    }
                    else
                    {
                        this.ViewModel.TetraModel = new Tetra();
                    }
                };

                this.lbTetraItems.ContextMenu.Opened += delegate
                {
                    if (this.lbTetraItems.SelectedItems != null && this.lbTetraItems.SelectedItems.Count > 0)
                    {
                        this.ViewModel.TetraModel = this.lbTetraItems.SelectedItem as Tetra;
                    }
                    else
                    {
                        this.ViewModel.TetraModel = new Tetra();
                    }
                };
                #endregion

                #region 远程主机存在的Config文件列表事件
                this.lbRemoteConfigFileItems.ContextMenu.Opened += delegate
                {
                    if (this.lbRemoteConfigFileItems.SelectedItems != null && this.lbRemoteConfigFileItems.SelectedItems.Count > 0)
                    {
                        this.ViewModel.ConfigFileModel = this.lbRemoteConfigFileItems.SelectedItem as ConfigFileModel;
                    }
                    else
                    {
                        this.ViewModel.ConfigFileModel = new ConfigFileModel();
                    }
                };
                #endregion

                this.lbRemoteTestLogItems.ContextMenu.Opened += delegate
                {
                    if (this.lbRemoteTestLogItems.SelectedItems != null && this.lbRemoteTestLogItems.SelectedItems.Count > 0)
                    {
                        this.ViewModel.TestLogFileModel = this.lbRemoteTestLogItems.SelectedItem as TetraTestLogModel;
                    }
                    else
                    {
                        this.ViewModel.TestLogFileModel = new TetraTestLogModel();
                    }
                };

                this.WindowState = WindowState.Maximized;
            };

            #endregion

            this.Closed += delegate
            {
                //if(honeyWell3320Helper1!= null)
                //{
                //    honeyWell3320Helper1.Close();
                //}
                //if (honeyWell3320Helper2 != null)
                //{
                //    honeyWell3320Helper2.Close();
                //}

                if (cts != null && task != null)
                {
                    cts.Cancel();
                    //Task.WaitAll(new Task[] { task });
                }
                //cts1.Cancel(); cts2.Cancel(); cts3.Cancel(); cts4.Cancel(); cts5.Cancel(); cts6.Cancel();
                //Task.WaitAll(new Task[] { task1, task2, task3, task4, task5, task6 });
            };

            #region Window KeyDown
            this.KeyDown += (sender, e) =>
            {
                if (e.Key == Key.F5)
                {
                    //OnClick("StartTest");
                }
                if (e.Key == Key.F1)
                {
                    
                }
            };
            #endregion
        }
        #region InitScanSerial
        public void InitScanTCP1()
        {
            honeyWell3320TCPHelper1 = new HoneyWell3320TCPHelper();

            honeyWell3320TCPHelper1.TCPConnectChange += (sender, isConnect)=>{

                if (isConnect)
                {
                    this.ViewModel.ScanStatus1.Update(string.Format("{0}:Scan1 is Connected", ViewModel.Setting.Scan1IPAddress), MyBrushes.Green);
                }
                else
                {
                    this.ViewModel.ScanStatus1.Update(string.Format("{0}:Scan1 is DisConnected", ViewModel.Setting.Scan1IPAddress), MyBrushes.Red);
                }

            };
            honeyWell3320TCPHelper1.TCPDataChange += (sender, data) =>
            {
                LogHelper.Info("NTC#1 Scan Barcode:" + data);

                this.Dispatcher.Invoke(() =>
                {
                    PowerONTest("NTC#1", data);
                });

                //honeyWell3320TCPHelper1.ReConnect();
            };

            honeyWell3320TCPHelper1.Initialize(ViewModel.Setting.Scan1IPAddress, ViewModel.Setting.Scan1PortNum);
        }

        public void InitScanTCP2()
        {
            honeyWell3320TCPHelper2 = new HoneyWell3320TCPHelper();

            honeyWell3320TCPHelper2.TCPConnectChange += (sender, isConnect) => {

                if (isConnect)
                {
                    this.ViewModel.ScanStatus2.Update(string.Format("{0}:Scan1 is Connected", ViewModel.Setting.Scan2IPAddress), MyBrushes.Green);
                }
                else
                {
                    this.ViewModel.ScanStatus2.Update(string.Format("{0}:Scan1 is DisConnected", ViewModel.Setting.Scan2IPAddress), MyBrushes.Red);
                }

            };
            honeyWell3320TCPHelper2.TCPDataChange += (sender, data) =>
            {
                LogHelper.Info("NTC#2 Scan Barcode:" + data);

                this.Dispatcher.Invoke(() =>
                {
                    PowerONTest("NTC#2", data);
                });

                //honeyWell3320TCPHelper1.ReConnect();
            };

            honeyWell3320TCPHelper2.Initialize(ViewModel.Setting.Scan2IPAddress, ViewModel.Setting.Scan2PortNum);
        }
        //public void InitScanSerial1()
        //{
        //    honeyWell3320Helper1 = new HoneyWell3320Helper(ViewModel.Setting.Scan1PortName);
        //    honeyWell3320Helper1.OnConnectedChanged += HoneyWell3320Helper1_OnConnectedChanged;
        //    honeyWell3320Helper1.OnScanBarcodeReceiveChanged += HoneyWell3320Helper1_OnScanBarcodeReceiveChanged;
        //    honeyWell3320Helper1.OnError += (sender, e) =>
        //    {
        //       LogHelper.Error(e.Exception, e.Title);
        //    };

        //    honeyWell3320Helper1.Connect("\r\n", 115200, 8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One);
        //}

        //private void HoneyWell3320Helper1_OnScanBarcodeReceiveChanged(string Barcode)
        //{
        //    Console.WriteLine("NTC#1 Scan Barcode:" + Barcode);
        //    this.Dispatcher.Invoke(() =>
        //    {
        //        PowerONTest("NTC#1", Barcode);
        //    });

        //}

        //private void HoneyWell3320Helper1_OnConnectedChanged(HoneyDeviceBase sender, bool isConnect)
        //{
        //    if (isConnect)
        //    {
        //        this.ViewModel.ScanStatus1.Update(string.Format("{0}:Scan1 is Connected",ViewModel.Setting.Scan1PortName), MyBrushes.Green);
        //    }
        //    else
        //    {
        //        this.ViewModel.ScanStatus1.Update(string.Format("{0}:Scan1 is DisConnected",ViewModel.Setting.Scan1PortName), MyBrushes.Red);
        //    }
        //}

        //public void InitScanSerial2()
        //{
        //    honeyWell3320Helper2 = new HoneyWell3320Helper(ViewModel.Setting.Scan2PortName);
        //    honeyWell3320Helper2.OnConnectedChanged += HoneyWell3320Helper2_OnConnectedChanged;
        //    honeyWell3320Helper2.OnScanBarcodeReceiveChanged += HoneyWell3320Helper2_OnScanBarcodeReceiveChanged;
        //    honeyWell3320Helper2.OnError += (sender, e) =>
        //    {
        //        LogHelper.Error(e.Exception, e.Title);
        //    };

        //    honeyWell3320Helper2.Connect("\r\n", 115200, 8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One);
        //}

        //private void HoneyWell3320Helper2_OnScanBarcodeReceiveChanged(string Barcode)
        //{
        //    Console.WriteLine("NTC#2 Scan Barcode:" + Barcode);
        //    this.Dispatcher.Invoke(() =>
        //    {
        //        PowerONTest("NTC#2", Barcode);
        //    });

        //}

        //private void HoneyWell3320Helper2_OnConnectedChanged(HoneyDeviceBase sender, bool isConnect)
        //{
        //    if (isConnect)
        //    {
        //        this.ViewModel.ScanStatus2.Update(string.Format("{0}:Scan2 is Connected",ViewModel.Setting.Scan2PortName), MyBrushes.Green);
        //    }
        //    else
        //    {
        //        this.ViewModel.ScanStatus2.Update(string.Format("{0}:Scan2 is DisConnected",ViewModel.Setting.Scan2PortName), MyBrushes.Red);
        //    }
        //}

        #endregion

        #region OpenPLCLink
        private async void OpenPLC()
        {
            m_MelsecPLCHelper = new MelsecPLCHelper(ViewModel.PLC_IPName, ViewModel.PLC_PortName);
            if (await m_MelsecPLCHelper.Open() != -1)
            {
                ViewModel.IsPLCConnect = true;
                if (!ConfigHelper.GetValueToBoolean("IsPLCDebug"))
                {
                    LinkPLCFrist = true;
                    
                    this.Dispatcher.Invoke(()=>{
                        ReadAddressState();
                    });
                   
                }
            }
            else
            {
                //if (!ViewModel.IsPLCConnect)
                //{
                //    OpenPLC();
                //}
            }
        }

        int preAOIState1 = 0;

        int preAOIState2 = 0;

        int preACState1 = 0;

        int preACState2 = 0;

        //int preNTCState1 = 0;

        //int preNTCState2 = 0;

        Task task = null;
        CancellationTokenSource cts = null;//new CancellationTokenSource();

        #region task delete
        //Task task1 = null;
        //Task task2 = null;
        //Task task3 = null;
        //Task task4 = null;
        //Task task5 = null;
        //Task task6 = null;


        //CancellationTokenSource cts1 = new CancellationTokenSource();
        //CancellationTokenSource cts2 = new CancellationTokenSource();
        //CancellationTokenSource cts3 = new CancellationTokenSource();
        //CancellationTokenSource cts4 = new CancellationTokenSource();
        //CancellationTokenSource cts5 = new CancellationTokenSource();
        //CancellationTokenSource cts6 = new CancellationTokenSource();

        //private  void ReadAddressState()
        //{
        //    try
        //    {
        //        AppendPLCTestData("AOI#1异步任务", MyBrushes.RichYellow);
        //        task1 = Task.Run(async () =>
        //        {
        //            while (!cts1.IsCancellationRequested)
        //            {
        //                if (m_MelsecPLCHelper != null)
        //                {
        //                    if (ViewModel.IsPLCConnect)
        //                    {
        //                        int[] AOIcurrentFlag1 = await m_MelsecPLCHelper.GetBitValue(ViewModel.ReadAOIAddress1, 1);

        //                        Console.WriteLine("iiii");

        //                        if (AOIcurrentFlag1 != null)
        //                        {
        //                            //foreach (int flag in AOIcurrentFlag1)
        //                            //{
        //                            //    this.ThreadSafe(delegate
        //                            //    {
        //                            //        PowerONTest("AOI#1");
        //                            //        AppendPLCTestData("AOI#1->>" + flag, MyBrushes.TESTING);
        //                            //    }, false);
        //                            //    AppendPLCTestData("AOI#1->>" + flag, MyBrushes.TESTING);
        //                            //}
        //                            if(AOIcurrentFlag1.Count() > 0)
        //                            {
        //                                int currentAOIState = AOIcurrentFlag1[0];

        //                                if(currentAOIState - preAOIState1 == 1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerONTest("AOI#1");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerON AOI#1->>" + currentAOIState, MyBrushes.TESTING);
        //                                }
        //                                else if(currentAOIState - preAOIState1 == -1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerOFFTest("AOI#1");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerOFF AOI#1->>" + currentAOIState, MyBrushes.TESTING);
        //                                }

        //                                preAOIState1 = currentAOIState;
        //                            }

        //                        }
        //                        else
        //                        {
        //                            if (ViewModel.IsPLCConnect)
        //                            {
        //                                m_MelsecPLCHelper.Close();

        //                                m_MelsecPLCHelper = null;
        //                                ViewModel.IsPLCConnect = false;

        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    break;
        //                }
        //            }
        //        },cts1.Token);

        //        AppendPLCTestData("AOI#2异步任务", MyBrushes.RichYellow);
        //        task2 = Task.Run(async () =>
        //        {
        //            while (!cts2.IsCancellationRequested)
        //            {
        //                if (m_MelsecPLCHelper != null)
        //                {
        //                    if (ViewModel.IsPLCConnect)
        //                    {
        //                        int[] AOIcurrentFlag2 = await m_MelsecPLCHelper.GetBitValue(ViewModel.ReadAOIAddress2, 1);

        //                        if (AOIcurrentFlag2 != null)
        //                        {
        //                            //foreach (int flag in AOIcurrentFlag2)
        //                            //{
        //                            //    this.ThreadSafe(delegate
        //                            //    {
        //                            //        PowerONTest("AOI#2");
        //                            //    },false);
        //                            //    AppendPLCTestData("AOI#2->>" + flag, MyBrushes.TESTING);
        //                            //}
        //                            if (AOIcurrentFlag2.Count() > 0)
        //                            {
        //                                int currentAOIState = AOIcurrentFlag2[0];

        //                                if (currentAOIState - preAOIState2 == 1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerONTest("AOI#2");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerON AOI#2->>" + currentAOIState, MyBrushes.TESTING);
        //                                }
        //                                else if (currentAOIState - preAOIState2 == -1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerOFFTest("AOI#2");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerOFF AOI#2->>" + currentAOIState, MyBrushes.TESTING);
        //                                }

        //                                preAOIState2 = currentAOIState;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            if (ViewModel.IsPLCConnect)
        //                            {
        //                                m_MelsecPLCHelper.Close();

        //                                m_MelsecPLCHelper = null;
        //                                ViewModel.IsPLCConnect = false;

        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    break;
        //                }
        //            }

        //        },cts2.Token);

        //        AppendPLCTestData("AC#1异步任务", MyBrushes.RichYellow);
        //        task3 = Task.Run(async () =>
        //        {
        //            while (!cts3.IsCancellationRequested)
        //            {
        //                if (m_MelsecPLCHelper != null)
        //                {
        //                    if (ViewModel.IsPLCConnect)
        //                    {
        //                        int[] ACcurrentFlag1 = await m_MelsecPLCHelper.GetBitValue(ViewModel.ReadACAddress1, 1);

        //                        if (ACcurrentFlag1 != null)
        //                        {
        //                            //foreach (int flag in ACcurrentFlag1)
        //                            //{
        //                            //    this.ThreadSafe(delegate
        //                            //    {
        //                            //        PowerONTest("AC#1");
        //                            //    },false);
        //                            //    AppendPLCTestData("AC#1->>" + flag, MyBrushes.TESTING);
        //                            //}
        //                            if (ACcurrentFlag1.Count() > 0)
        //                            {
        //                                int currentACState = ACcurrentFlag1[0];

        //                                if (currentACState - preACState1 == 1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerONTest("AC#1");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerON AC#1->>" + currentACState, MyBrushes.TESTING);
        //                                }
        //                                else if (currentACState - preACState1 == -1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerOFFTest("AC#1");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerOFF AC#1->>" + currentACState, MyBrushes.TESTING);
        //                                }

        //                                preACState1 = currentACState;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            if (ViewModel.IsPLCConnect)
        //                            {
        //                                m_MelsecPLCHelper.Close();

        //                                m_MelsecPLCHelper = null;
        //                                ViewModel.IsPLCConnect = false;

        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    break;
        //                }
        //            }

        //        },cts3.Token);

        //        AppendPLCTestData("AC#2异步任务", MyBrushes.RichYellow);
        //        task4 = Task.Run(async () =>
        //        {
        //            while (!cts4.IsCancellationRequested)
        //            {

        //                if (m_MelsecPLCHelper != null)
        //                {
        //                    if (ViewModel.IsPLCConnect)
        //                    {
        //                        int[] ACcurrentFlag2 = await m_MelsecPLCHelper.GetBitValue(ViewModel.ReadACAddress2, 1);
        //                        if (ACcurrentFlag2 != null)
        //                        {
        //                            //foreach (int flag in ACcurrentFlag2)
        //                            //{
        //                            //    this.ThreadSafe(delegate
        //                            //    {
        //                            //        PowerONTest("AC#2");
        //                            //    }, false);
        //                            //    AppendPLCTestData("AC#2->>" + flag, MyBrushes.TESTING);
        //                            //}
        //                            if (ACcurrentFlag2.Count() > 0)
        //                            {
        //                                int currentACState = ACcurrentFlag2[0];

        //                                if (currentACState - preACState2 == 1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerONTest("AC#2");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerON AC#2->>" + currentACState, MyBrushes.TESTING);
        //                                }
        //                                else if (currentACState - preACState2 == -1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerOFFTest("AC#2");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerOFF AC#2->>" + currentACState, MyBrushes.TESTING);
        //                                }

        //                                preACState2 = currentACState;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            if (ViewModel.IsPLCConnect)
        //                            {
        //                                m_MelsecPLCHelper.Close();

        //                                m_MelsecPLCHelper = null;
        //                                ViewModel.IsPLCConnect = false;

        //                                break;
        //                            }
        //                        }
        //                    }

        //                }
        //                else
        //                {
        //                    break;
        //                }
        //            }

        //        },cts4.Token);

        //        AppendPLCTestData("NTC#1异步任务", MyBrushes.RichYellow);
        //        task5 = Task.Run(async () =>
        //        {
        //            while (!cts5.IsCancellationRequested)
        //            {
        //                if (m_MelsecPLCHelper != null)
        //                {
        //                    if (ViewModel.IsPLCConnect)
        //                    {
        //                        int[] NTCcurrentFlag1 = await m_MelsecPLCHelper.GetBitValue(ViewModel.ReadNTCAddress1, 1);
        //                        if (NTCcurrentFlag1 != null)
        //                        {
        //                            //foreach (int flag in NTCcurrentFlag1)
        //                            //{
        //                            //    this.ThreadSafe(delegate
        //                            //    {
        //                            //        PowerONTest("NTC#1");
        //                            //    }, false);
        //                            //    AppendPLCTestData("NTC#1->>" + flag, MyBrushes.TESTING);
        //                            //}
        //                            if (NTCcurrentFlag1.Count() > 0)
        //                            {
        //                                int currentNTCState = NTCcurrentFlag1[0];

        //                                if (currentNTCState - preNTCState1 == 1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerONTest("NTC#1");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerON NTC#1->>" + currentNTCState, MyBrushes.TESTING);
        //                                }
        //                                else if (currentNTCState - preNTCState1 == -1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerOFFTest("NTC#1");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerOFF NTC#1->>" + currentNTCState, MyBrushes.TESTING);
        //                                }

        //                                preNTCState1 = currentNTCState;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            if (ViewModel.IsPLCConnect)
        //                            {
        //                                m_MelsecPLCHelper.Close();
        //                                m_MelsecPLCHelper = null;
        //                                ViewModel.IsPLCConnect = false;
        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    break;
        //                }
        //            }

        //        },cts5.Token);

        //        AppendPLCTestData("NTC#2异步任务", MyBrushes.RichYellow);
        //        task6 = Task.Run(async () =>
        //        {
        //            while (!cts6.IsCancellationRequested)
        //            {
        //                if (m_MelsecPLCHelper != null)
        //                {
        //                    if (ViewModel.IsPLCConnect)
        //                    {
        //                        int[] NTCcurrentFlag2 = await m_MelsecPLCHelper.GetBitValue(ViewModel.ReadNTCAddress2, 1);

        //                        if (NTCcurrentFlag2 != null)
        //                        {
        //                            //foreach (int flag in NTCcurrentFlag2)
        //                            //{
        //                            //    this.ThreadSafe(delegate
        //                            //    {
        //                            //        PowerONTest("NTC#2");
        //                            //    }, false);
        //                            //    AppendPLCTestData("NTC#2->>" + flag, MyBrushes.TESTING);
        //                            //}
        //                            if (NTCcurrentFlag2.Count() > 0)
        //                            {
        //                                int currentNTCState = NTCcurrentFlag2[0];

        //                                if (currentNTCState - preNTCState2 == 1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerONTest("NTC#2");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerON NTC#2->>" + currentNTCState, MyBrushes.TESTING);
        //                                }
        //                                else if (currentNTCState - preNTCState2 == -1)
        //                                {
        //                                    this.ThreadSafe(delegate
        //                                    {
        //                                        PowerOFFTest("NTC#2");

        //                                    }, false);
        //                                    AppendPLCTestData("PowerOFF NTC#2->>" + currentNTCState, MyBrushes.TESTING);
        //                                }

        //                                preNTCState2 = currentNTCState;
        //                            }
        //                        }
        //                        else
        //                        {
        //                            if (ViewModel.IsPLCConnect)
        //                            {
        //                                m_MelsecPLCHelper.Close();
        //                                m_MelsecPLCHelper = null;
        //                                ViewModel.IsPLCConnect = false;
        //                                break;
        //                            }
        //                        }
        //                    }
        //                }
        //                else
        //                {
        //                    break;
        //                }
        //            }

        //        },cts6.Token);
        //    }
        //    catch(Exception ex)
        //    {
        //        LogHelper.Error(ex);
        //    }
        //}
        #endregion

        private void ReadAddressState()
        {
            try
            {
                AppendPLCTestData("异步任务", MyBrushes.RichYellow);

                cts = new CancellationTokenSource();

                task = Task.Run(async () =>
                {
                    while (!cts.IsCancellationRequested)
                    {
                        if (m_MelsecPLCHelper != null)
                        {
                            if (ViewModel.IsPLCConnect)
                            {
                                int[] currentFlag = await m_MelsecPLCHelper.GetBitValue(ViewModel.ReadAOIAddress1, 4);

                                if (currentFlag != null && currentFlag.Count() > 3)
                                {
                                    int index = 0;
                                    foreach (var item in currentFlag)
                                    {

                                        Console.WriteLine("currentFlag" + (++index).ToString() +":" + item);

                                    }

                                    int currentAOIState1 = currentFlag[0];
                                    int currentAOIState2 = currentFlag[1];
                                    int currentACState1 =  currentFlag[2];
                                    int currentACState2 =  currentFlag[3];

                                    ViewModel.ReadAddressValue = currentAOIState1 + "," + currentAOIState2 + "," + currentACState1 + "," + currentACState2;
                                    //int currentNTCState1 = currentFlag[4];
                                    //int currentNTCState2 = currentFlag[5];
                                    if (LinkPLCFrist)
                                    {
                                        preAOIState1 = currentAOIState1;
                                        preAOIState2 = currentAOIState2;
                                        preACState1 = currentACState1;
                                        preACState2 = currentACState2;

                                        LinkPLCFrist = false;

                                        continue;
                                    }

                                    if (currentAOIState1 - preAOIState1 == 1)
                                    {
                                        this.ThreadSafe(delegate
                                        {
                                            PowerONTest("AOI#1");

                                        }, false);
                                        AppendPLCTestData("PowerON AOI#1->>" + currentAOIState1, MyBrushes.TESTING);
                                    }
                                    else if (currentAOIState1 - preAOIState1 == -1)
                                    {
                                        this.ThreadSafe(delegate
                                        {
                                            PowerOFFTest("AOI#1");

                                        }, false);
                                        AppendPLCTestData("PowerOFF AOI#1->>" + currentAOIState1, MyBrushes.TESTING);
                                    }

                                    if (currentAOIState2 - preAOIState2 == 1)
                                    {
                                        this.ThreadSafe(delegate
                                        {
                                            PowerONTest("AOI#2");

                                        }, false);
                                        AppendPLCTestData("PowerON AOI#2->>" + currentAOIState2, MyBrushes.TESTING);
                                    }
                                    else if (currentAOIState2 - preAOIState2 == -1)
                                    {
                                        this.ThreadSafe(delegate
                                        {
                                            PowerOFFTest("AOI#2");

                                        }, false);
                                        AppendPLCTestData("PowerOFF AOI#2->>" + currentAOIState2, MyBrushes.TESTING);
                                    }

                                    if (currentACState1 - preACState1 == 1)
                                    {
                                        this.ThreadSafe(delegate
                                        {
                                            PowerONTest("AC#1");

                                        }, false);
                                        AppendPLCTestData("PowerON AC#1->>" + currentACState1, MyBrushes.TESTING);
                                    }
                                    else if (currentACState1 - preACState1 == -1)
                                    {
                                        this.ThreadSafe(delegate
                                        {
                                            PowerOFFTest("AC#1");

                                        }, false);
                                        AppendPLCTestData("PowerOFF AC#1->>" + currentACState1, MyBrushes.TESTING);
                                    }

                                    if (currentACState2 - preACState2 == 1)
                                    {
                                        this.ThreadSafe(delegate
                                        {
                                            PowerONTest("AC#2");

                                        }, false);
                                        AppendPLCTestData("PowerON AC#2->>" + currentACState2, MyBrushes.TESTING);
                                    }
                                    else if (currentACState2 - preACState2 == -1)
                                    {
                                        this.ThreadSafe(delegate
                                        {
                                            PowerOFFTest("AC#2");

                                        }, false);
                                        AppendPLCTestData("PowerOFF AC#2->>" + currentACState2, MyBrushes.TESTING);
                                    }

                                    //if (currentNTCState1 - preNTCState1 == 1)
                                    //{
                                    //    this.ThreadSafe(delegate
                                    //    {
                                    //        PowerONTest("NTC#1");

                                    //    }, false);
                                    //    AppendPLCTestData("PowerON NTC#1->>" + currentNTCState1, MyBrushes.TESTING);
                                    //}
                                    //else if (currentNTCState1 - preNTCState1 == -1)
                                    //{
                                    //    this.ThreadSafe(delegate
                                    //    {
                                    //        PowerOFFTest("NTC#1");

                                    //    }, false);
                                    //    AppendPLCTestData("PowerOFF NTC#1->>" + currentNTCState1, MyBrushes.TESTING);
                                    //}

                                    //if (currentNTCState2 - preNTCState2 == 1)
                                    //{
                                    //    this.ThreadSafe(delegate
                                    //    {
                                    //        PowerONTest("NTC#2");

                                    //    }, false);
                                    //    AppendPLCTestData("PowerON NTC#2->>" + currentNTCState2, MyBrushes.TESTING);
                                    //}
                                    //else if (currentNTCState2 - preNTCState2 == -1)
                                    //{
                                    //    this.ThreadSafe(delegate
                                    //    {
                                    //        PowerOFFTest("NTC#2");

                                    //    }, false);
                                    //    AppendPLCTestData("PowerOFF NTC#2->>" + currentNTCState2, MyBrushes.TESTING);
                                    //}

                                    preAOIState1 = currentAOIState1;
                                    preAOIState2 = currentAOIState2;

                                    preACState1 = currentACState1;
                                    preACState2 = currentACState2;

                                    //preNTCState1 = currentNTCState1;
                                    //preNTCState2 = currentNTCState2;

                                }
                                else
                                {
                                    if (ViewModel.IsPLCConnect)
                                    {
                                        m_MelsecPLCHelper.Close();

                                        m_MelsecPLCHelper = null;
                                        ViewModel.IsPLCConnect = false;

                                        break;
                                    }
                                }
                            }
                          
                        }
                        else
                        {
                            break;
                        }
                    }
                }, cts.Token);


            }
            catch(Exception ex) { LogHelper.Error(ex);}
        }

        private async void PCToPLCSend(string AddressName, int[] data)
        {
            if (m_MelsecPLCHelper != null)
            {
                if (!ConfigHelper.GetValueToBoolean("IsPLCDebug"))
                {
                    LogHelper.Info("PC--->PLC:" + AddressName + "Data:" + (data.Count() > 0 ? data[0].ToString():"error count=0"));
                    //await m_MelsecPLCHelper.SetBitValues(AddressName, data);
                    if (ViewModel.IsPLCConnect)
                    {
                        await m_MelsecPLCHelper.SetBlockValue(AddressName, data);
                    }
                    else
                    {
                        this.ShowPromptWindow("PLC 未连接", PromptType.Red);
                    }
                }
            }
        }

        #endregion

        #region OnClick Event
        private void OnClick(object parameter)
        {
            if (parameter != null)
            {
                switch (parameter.ToString())
                {
                    case "Operator":
                        {
                            ChangePage(this.GridOperator);
                        }
                        break;
                    case "ChangeModel":
                        {
                            System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
                            Application.Current.Shutdown();
                        }
                        break;
                    case "Engineer":
                        {
                            //foreach (TestStation testStation in ViewModel.TestStations)
                            //{
                            //    if (!testStation.TestInfo.EnabledStartButton)
                            //    {
                            //        this.ShowPromptWindow("正在测试中，请稍后", PromptType.Red);
                            //        return;
                            //    }

                            //}
                            //var localRegistry = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", true).CreateSubKey("BambooPlus", Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree).CreateSubKey("Info", Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree);
                            string pwd = "TPKETC";//+ DateTime.Now.ToString("yyyyMMdd");
#if DEBUG

                            pwd = "";

#endif
                            ViewModel.IsLogin = this.ShowPasswordDialog("Engineer Login", pwd);

                            if (ViewModel.IsLogin == true)
                            {

                                foreach (TestStation testStation in ViewModel.TestStations)
                                {
                                    int index = ViewModel.TestStations.IndexOf(testStation);

                                    var dependObj = itemsStation.ItemContainerGenerator.ContainerFromIndex(index);

                                    var ucStation = WPFHelper.FindVisualChildItem<UserControls.UcTestStation>(dependObj, "ucTestStationName");

                                    if (ucStation != null)
                                    {
                                        ucStation.IsEngineer = true;
                                    }
                                }

                            }
                        }
                        break;
                    case "Logout":
                        {
                            ViewModel.IsLogin = false;

                            foreach (TestStation testStation in ViewModel.TestStations)
                            {
                                int index = ViewModel.TestStations.IndexOf(testStation);

                                var dependObj = itemsStation.ItemContainerGenerator.ContainerFromIndex(index);

                                var ucStation = WPFHelper.FindVisualChildItem<UserControls.UcTestStation>(dependObj, "ucTestStationName");

                                if (ucStation != null)
                                {
                                    ucStation.IsEngineer = false;
                                }
                            }

                            ChangePage(this.GridOperator);
                        }
                        break;
                    case "StartTest":
                        {
                            #region startallTest
                            //foreach (TestStation testStation in ViewModel.TestStations)
                            //{

                            //    int index = ViewModel.TestStations.IndexOf(testStation);

                            //    var dependObj = itemsStation.ItemContainerGenerator.ContainerFromIndex(index);

                            //    var ucStation = WPFHelper.FindVisualChildItem<UserControls.UcTestStation>(dependObj, "ucTestStationName");

                            //    if (ucStation != null && ucStation.TestStation != null && ucStation.TestStation.TestInfo != null)
                            //    {
                            //        ucStation.IsMultiStationStart = true;

                            //        if (ucStation.TestStation.TestInfo.EnabledStartButton)
                            //        {
                            //            ucStation.OnStartTestResultChanged -= UcStation_OnStartTestResultChanged;
                            //            ucStation.OnStartTestResultChanged += UcStation_OnStartTestResultChanged;

                            //            ucStation.StartTest();

                            //        }
                            //        else
                            //        {
                            //            this.ShowPromptWindow("请确认设备是否连接？", PromptType.Red);
                            //        }
                            //    }

                            //}

                            //this.Loading.Show("Testing...");

                            //Task.Factory.StartNew(() =>
                            //{
                            //    while (true)
                            //    {
                            //        bool isEndTest = true;

                            //        foreach (TestStation testStation in ViewModel.TestStations)
                            //        {
                            //            if (testStation.TestInfo.IsTesting)
                            //            {
                            //                isEndTest = false;
                            //            }
                            //        }

                            //        if (isEndTest)
                            //        {
                            //            break;
                            //        }
                            //    }

                            //}).ContinueWith(t =>
                            //{
                            //    WriteTestLog(ViewModel.TestStations);
                            //    Console.WriteLine("End..............");
                            //    this.Loading.Hide();

                            //});
                            #endregion
                        }
                        break;
                    #region Power ON or OFF
                    case "AOI#1PowerONTest":
                        {
                            PowerONTest("AOI#1");
                        }
                        break;
                    case "AOI#2PowerONTest":
                        {
                            PowerONTest("AOI#2");
                        }
                        break;
                    case "AC#1PowerONTest":
                        {
                            PowerONTest("AC#1");
                        }
                        break;
                    case "AC#2PowerONTest":
                        {
                            PowerONTest("AC#2");

                        }
                        break;
                    case "NTC#1PowerONTest":
                        {
                            PowerONTest("NTC#1");
                        }
                        break;
                    case "NTC#2PowerONTest":
                        {
                            PowerONTest("NTC#2");
                        }
                        break;
                    case "AOI#1PowerOFFTest":
                        {
                            PowerOFFTest("AOI#1");
                        }
                        break;
                    case "AOI#2PowerOFFTest":
                        {
                            PowerOFFTest("AOI#2");
                        }
                        break;
                    case "AC#1PowerOFFTest":
                        {
                            PowerOFFTest("AC#1");
                        }
                        break;
                    case "AC#2PowerOFFTest":
                        {
                            PowerOFFTest("AC#2");
                        }
                        break;
                    case "NTC#1PowerOFFTest":
                        {
                            PowerOFFTest("NTC#1");
                        }
                        break;
                    case "NTC#2PowerOFFTest":
                        {
                            PowerOFFTest("NTC#2");
                        }
                        break;
                    case "PowerOFFTest":
                        {
                            //foreach (TestStation testStation in ViewModel.TestStations)
                            //{
                            //    int index = ViewModel.TestStations.IndexOf(testStation);

                            //    var dependObj = itemsStation.ItemContainerGenerator.ContainerFromIndex(index);

                            //    var ucStation = WPFHelper.FindVisualChildItem<UserControls.UcTestStation>(dependObj, "ucTestStationName");

                            //    if (ucStation != null && ucStation.TestStation != null)
                            //    {
                            //        if (ucStation.TestStation.IsStop)
                            //        {
                            //            //ucStation.TestStation.IsPowerOFF = true;
                            //            ucStation.OnStartTestResultChanged -= UcStation_OnStartTestResultChanged;
                            //        }

                            //    }

                            //}
                        }
                        break;
                    #endregion
                    case "OpenScanNTC#1":
                        {
                            if (honeyWell3320TCPHelper1.IsConnected)
                            {

                                this.Loading.Show("Scan NTC#1");

                                string code = string.Empty;

                                Task.Factory.StartNew(() =>
                                {

                                    code = honeyWell3320TCPHelper1.OpenScanBarcode();

                                }).ContinueWith(t =>
                                {
                                    this.Dispatcher.Invoke(() =>
                                    {
                                        this.ShowPromptWindow(code, PromptType.Green);

                                    });

                                    honeyWell3320TCPHelper1.CloseScanBarcode();

                                    this.Loading.Hide();
                                });
                            }
                            else
                            {
                                this.ShowPromptWindow("扫描枪1未连接，请检查", PromptType.Red);
                            }
                        }
                        break;
                    case "OpenScanNTC#2":
                        {
                            if (honeyWell3320TCPHelper2.IsConnected)
                            {

                                this.Loading.Show("Scan NTC#2");

                                string code = string.Empty;

                                Task.Factory.StartNew(() =>
                                {

                                    code = honeyWell3320TCPHelper2.OpenScanBarcode();

                                }).ContinueWith(t =>
                                {
                                    this.Dispatcher.Invoke(() =>
                                    {
                                        this.ShowPromptWindow(code, PromptType.Green);

                                    });

                                    honeyWell3320TCPHelper2.CloseScanBarcode();

                                    this.Loading.Hide();
                                });
                            }
                            else
                            {
                                this.ShowPromptWindow("扫描枪2未连接，请检查", PromptType.Red);
                            }
                        }
                        break;
                    case "StopTest":
                        {
                            ////this.StopTest();
                            //foreach (TestStation testStation in ViewModel.TestStations)
                            //{
                            //    int index = ViewModel.TestStations.IndexOf(testStation);

                            //    var dependObj = itemsStation.ItemContainerGenerator.ContainerFromIndex(index);

                            //    var ucStation = WPFHelper.FindVisualChildItem<UserControls.UcTestStation>(dependObj, "ucTestStationName");

                            //    if (ucStation != null && ucStation.TestStation != null)
                            //    {
                            //        if (ucStation.TestStation.IsStop)
                            //        {
                            //            ucStation.TestStation.IsStop = false;

                            //        }

                            //    }

                            //}
                        }
                        break;
                    case "PLCOperation":
                        {
                            string pwd = "TPKETC";//+ DateTime.Now.ToString("yyyyMMdd");
#if DEBUG

                            pwd = "";

#endif
                            bool isYes = this.ShowPasswordDialog("PLC Control", pwd);

                            if (isYes == true)
                            {
                                ChangePage(this.GridPLCOperator);
                            }
                            else
                            {
                                this.ShowPromptWindow("密码错误!", PromptType.Red);
                            }
                        }
                        break;
                    case "PLCLink":
                        {
                            this.Loading.Show("Link PLC ...");
                            Task.Factory.StartNew(() =>
                            {
                                this.OpenPLC();

                            }).ContinueWith(t =>
                            {
                                this.Loading.Hide();
                            });
                        }
                        break;
                    case "CancelLoop":
                        {

                        }
                        break;
                    case "TestConfig":
                        {
                            //ShowWindow<Windows.FrmConfig>(this);
                        }
                        break;
                    case "Setting":
                        {
                            ShowWindow<Windows.FrmSetting>(this);
                        }
                        break;
                    case "CheckUpdate":
                        if (!App.CheckUpdate())
                        {
                            this.ShowDialog(App.GetString("NotNeedUpdatePrompt"), App.GetString("Prompt"), MessageBoxButton.OK, Bandit.UI.DialogIcon.OK);
                        }
                        break;
                    case "About":
                        {
                            Windows.FrmAbout.Show(this);
                        }
                        break;
                    case "NewStation":
                        this.ShowStationEdiePanel();
                        break;
                    case "AddStation":
                        this.AddStation();
                        break;
                    case "Cancel":
                        this.HideStationEditPanel();
                        break;
                    case "Log":
                        {
                            string path = this.GetBaseDirectory() + "Log\\Info\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";

                            if (System.IO.File.Exists(path))
                            {
                                System.Diagnostics.Process.Start(path);

                                //string text = System.IO.File.ReadAllText(path);

                                //this.ShowText(new BanditTextViewModel() { Text = text });
                            }
                        }
                        break;
                    case "DeleteLog":
                        {
                            string path = this.GetBaseDirectory() + "Log\\Info\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";

                            if (System.IO.File.Exists(path))
                            {
                                try
                                {
                                    File.Delete(path);

                                    this.ShowPromptWindow("删除成功", PromptType.Green);

                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message);
                                }
                            }
                        }
                        break;
                    case "LogPath":
                        {
                            string path = this.GetBaseDirectory() + "Log\\";
                            if (System.IO.Directory.Exists(path))
                            {
                                System.Diagnostics.Process.Start(path);

                                //string text = System.IO.File.ReadAllText(path);

                                //this.ShowText(new BanditTextViewModel() { Text = text });
                            }
                        }
                        break;
                    case "ZipLog":
                        {
                            string debugLog = this.GetBaseDirectory() + "Log\\Debug\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                            string errorLog = this.GetBaseDirectory() + "Log\\Error\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                            string infoLog = this.GetBaseDirectory() + "Log\\Info\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";

                            List<string> paths = new List<string>();
                            if (System.IO.File.Exists(debugLog))
                            {
                                paths.Add(debugLog);
                            }
                            if (System.IO.File.Exists(errorLog))
                            {
                                paths.Add(errorLog);
                            }
                            if (System.IO.File.Exists(infoLog))
                            {
                                paths.Add(infoLog);
                            }

                            if (paths.Count > 0)
                            {
                                string zipFile = this.GetBaseDirectory() + "Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".zip";
                                Bandit.Zip.ZipHelper.ZipFiles(paths.ToArray(), zipFile);
                                Bandit.Helpers.FileHelper.PositionFile(zipFile);
                            }
                        }
                        break;
                    
                    #region Firmware
                    case "FirmwareOperation":
                        {
                            ChangePage(this.GridFirmWareOperator);
                        }
                        break;
                    case "Refresh":
                        {
                            this.Refresh();
                        }
                        break;
                    case "Add":
                        {
                            this.AddTetra();
                        }
                        break;
                    case "Edit":
                        {
                            this.EditTetra();
                        }
                        break;
                    case "Delete":
                        {
                            this.DeleteTetra();
                        }
                        break;
                    case "SaveJsonAndContinue":
                        {
                            this.Loading.Show();
                            Task.Factory.StartNew(() =>
                            {
                                JsonConfig.Instance.TetraItems.Add(this.ViewModel.TetraModel);

                                JsonConfig.SaveJsonConfig();

                                JsonConfig.LoadJsonConfig();

                                ViewModel.JsonConfig = JsonConfig.Instance;

                            }).ContinueWith(t =>
                            {

                                this.Dispatcher.Invoke(new Action(() =>
                                {

                                    this.lbTetraItems.ItemsSource = null;
                                    this.lbTetraItems.ItemsSource = ViewModel.JsonConfig.TetraItems;

                                    this.Loading.Hide();

                                    this.AddTetra();

                                }));

                            });
                        }
                        break;
                    case "SaveJson":
                        {
                            this.Loading.Show();

                            Task.Factory.StartNew(() =>
                            {
                                if (this.IsAdding)
                                {
                                    JsonConfig.Instance.TetraItems.Add(this.ViewModel.TetraModel);
                                }
                                else
                                {
                                    //Tetra tetra = 
                                    JsonConfig.Instance.TetraItems.Find(x => x.UserName == this.ViewModel.TetraModel.UserName);

                                    //tetra.Address = this.ViewModel.TetraModel.Address;
                                    //tetra.Name = this.ViewModel.TetraModel.Name;
                                    //tetra.Remark = this.ViewModel.TetraModel.Remark;

                                }

                                JsonConfig.SaveJsonConfig();

                                JsonConfig.LoadJsonConfig();

                                ViewModel.JsonConfig = JsonConfig.Instance;

                            }).ContinueWith(t =>
                            {

                                this.Dispatcher.Invoke(new Action(() =>
                                {

                                    this.lbTetraItems.ItemsSource = null;
                                    this.lbTetraItems.ItemsSource = ViewModel.JsonConfig.TetraItems;

                                    this.ucPanelEditTetra.Hide();

                                    this.Loading.Hide();

                                }));
                            });

                        }
                        break;
                    case "SelectProgramFile":
                        {
                            //_Tetra.SwitchIP(true);
                            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
                            ofd.Filter = "Tetra Upgrade Program|*.etc";
                            if (ofd.ShowDialog().Value)
                            {
                                this.txtProgramFile.Text = ofd.FileName;
                            }
                        }
                        break;
                    case "SelectTcgFiles":
                        {

                            //var dialog = new System.Windows.Forms.FolderBrowserDialog();
                            Bandit.UI.OpenFolderDialog dialog = new Bandit.UI.OpenFolderDialog();

                            string initialDirectory = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs");
                            if (!System.IO.Directory.Exists(initialDirectory))
                            {
                                System.IO.Directory.CreateDirectory(initialDirectory);
                            }

                            dialog.InitialFolder = initialDirectory;

                            if (dialog.ShowDialog(this.Owner))
                            {
                                ViewModel.TetraTcgFileInfoList = new ObservableCollection<TetraTcgFileInfo>();

                                string SelectedPath = dialog.Folder;

                                tbTcgDirtoryName.Text = SelectedPath;

                                string[] files = Directory.GetFiles(SelectedPath);

                                int i = 0;

                                foreach (string file in files)
                                {

                                    if (System.IO.Path.GetExtension(file).Contains(".tcg"))
                                    {
                                        TetraTcgFileInfo tetraTcgFileInfo = new TetraTcgFileInfo();

                                        tetraTcgFileInfo.Name = System.IO.Path.GetFileNameWithoutExtension(file);

                                        tetraTcgFileInfo.IsUpdata = true;

                                        tetraTcgFileInfo.FilePath = file;

                                        tetraTcgFileInfo.Num = ++i;

                                        ViewModel.TetraTcgFileInfoList.Add(tetraTcgFileInfo);
                                    }
                                }

                            }
                        }
                        break;
                    case "RefreshLocalConfigs":
                        {
                            string SelectedPath = tbTcgDirtoryName.Text;

                            if (SelectedPath == "")
                            {
                                this.ShowPromptWindow("请选择配置路径", PromptType.Red);
                                return;
                            }

                            ViewModel.TetraTcgFileInfoList = new ObservableCollection<TetraTcgFileInfo>();

                            string[] files = Directory.GetFiles(SelectedPath);

                            int i = 0;

                            foreach (string file in files)
                            {

                                if (System.IO.Path.GetExtension(file).Contains(".tcg"))
                                {
                                    TetraTcgFileInfo tetraTcgFileInfo = new TetraTcgFileInfo();

                                    tetraTcgFileInfo.Name = System.IO.Path.GetFileNameWithoutExtension(file);

                                    tetraTcgFileInfo.IsUpdata = true;

                                    tetraTcgFileInfo.FilePath = file;

                                    tetraTcgFileInfo.Num = ++i;

                                    ViewModel.TetraTcgFileInfoList.Add(tetraTcgFileInfo);
                                }
                            }
                        }
                        break;
                    case "DeleteProgramFile":
                        {
                            this.txtProgramFile.Clear();
                        }
                        break;
                    case "Upgrade":
                        {
                            Upgrade();
                        }
                        break;
                    case "UpgradeProgramAllDevice":
                        {
                            AllUpgrade();
                        }
                        break;
                    case "UpdateConfigFile":
                        {
                            UpdateConfigFile();
                        }
                        break;
                    case "UpadteConfigAllDevice":
                        {
                            UpdateConfigFileToAllDevice();
                        }
                        break;
                    case "DownloadPITestLog":
                        {
                            DownloadPITestLog();
                        }
                        break;
                    case "DownloadPILog":
                        {
                            DownloadPILog();
                        }
                        break;
                    case "DeleteConfigFile":
                        {
                            DeleteConfigFile();
                        }
                        break;
                    case "btnDeleteAllRemoteConfigsFile":
                        {
                            DeleteAllRemoteConfigsFile();
                        }
                        break;
                    case "RefreshRemoteConfigs":
                        {
                            this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

                            Task.Factory.StartNew(delegate
                            {
                                this.ViewModel.ConfigFileModels = new List<ConfigFileModel>();
                                this.ViewModel.RemoteTestLogModels = new ObservableCollection<TetraTestLogModel>();

                                if (_Tetra.Connect())
                                {
                                    //this.Refresh();
                                    RemoveLastBlockAppendLog();

                                    this.ViewModel.ConfigFileModels = _Tetra.GetRemoteConfigFile("Configs", ".tcg");

                                }
                                else
                                {
                                    RemoveLastBlockAppendLog();

                                    this.ShowPromptWindow("未能连接PI主机,请确认其是否在线", Bandit.UI.PromptType.Red, 2);

                                }
                            }).ContinueWith(task =>
                            {
                                if (task.IsFaulted)
                                {
                                    task.LogExceptions();
                                }

                                this.Dispatcher.Invoke(new Action(() =>
                                {
                                    this.lbRemoteConfigFileItems.ItemsSource = null;
                                    this.lbRemoteConfigFileItems.ItemsSource = this.ViewModel.ConfigFileModels;

                                }));

                            });
                        }
                        break;
                    case "DeleteTestLogFile":
                        {
                            DeleteTestLogFile();
                        }
                        break;
                    case "DeletePITestLog":
                        {
                            DeleteTestLogDir();
                        }
                        break;
                    case "DeletePILog":
                        {
                            DeleteLogDir();
                        }
                        break;
                    case "btnAllCheck":
                        {
                            foreach (TetraTcgFileInfo tetraTcgFileInfo in ViewModel.TetraTcgFileInfoList)
                            {
                                tetraTcgFileInfo.IsUpdata = true;
                            }
                        }
                        break;
                    case "btnInverseCheck":
                        {
                            foreach (TetraTcgFileInfo tetraTcgFileInfo in ViewModel.TetraTcgFileInfoList)
                            {
                                tetraTcgFileInfo.IsUpdata = false;
                            }
                        }
                        break;
                    case "BackTestLog":
                        {
                            if (RemoteTestLogPath != "TestLog")
                            {

                                string[] s = RemoteTestLogPath.Split("/");

                                RemoteTestLogPath = RemoteTestLogPath.Substring(0, RemoteTestLogPath.Length - s[s.Length - 1].Length - 1);

                                this.ViewModel.RemoteTestLogModels = _Tetra.GetRemoteTestLogFile(RemoteTestLogPath);

                                this.Dispatcher.Invoke(new Action(() =>
                                {
                                    ucTestLogName.Title = RemoteTestLogPath;

                                    this.lbRemoteTestLogItems.ItemsSource = null;
                                    this.lbRemoteTestLogItems.ItemsSource = this.ViewModel.RemoteTestLogModels;
                                }));
                            }
                        }
                        break;
                    case "btnTestLogAllCheck":
                        {
                            foreach (TetraTestLogModel tetraTestLogModel in ViewModel.RemoteTestLogModels)
                            {
                                tetraTestLogModel.IsDownLoad = true;
                            }
                        }
                        break;
                    case "btnTestLogInverseCheck":
                        {
                            foreach (TetraTestLogModel tetraTestLogModel in ViewModel.RemoteTestLogModels)
                            {
                                tetraTestLogModel.IsDownLoad = false;
                            }
                        }
                        break;
                    #endregion
                    default:
                        break;
                }
            }
        }

        #endregion

        #region 点灯关灯
        private void PowerONTest(string StationName,string Barcode = "0")
        {
            //if (ConfigHelper.GetValueToBoolean("IsPLCDebug"))
            //{
            //    this.ShowPromptWindow(("IsDebug True, Test:" + StationName).ToString(),PromptType.Yellow);
            //    return;
            //}

            TestStation testStation1 = ViewModel.TestStations.FirstOrDefault(s => s.TestInfo.StationName == StationName);

            if (testStation1 == null)
            {
                this.ShowPromptWindow(string.Format("不存在{0}站点",StationName), PromptType.Red);
                return;
            }

            foreach (TestStation testStation in ViewModel.TestStations)
            {
                int index = ViewModel.TestStations.IndexOf(testStation);

                var dependObj = itemsStation.ItemContainerGenerator.ContainerFromIndex(index);

                var ucStation = WPFHelper.FindVisualChildItem<UserControls.UcTestStation>(dependObj, "ucTestStationName");

                if (ucStation != null && ucStation.TestStation != null && ucStation.TestStation.TestInfo != null && ucStation.TestStation.TestInfo.StationName != null)
                {
                    ucStation.IsMultiStationStart = false;

                    if (ucStation.TestStation.TestInfo.StationName.Contains(StationName))
                    {
                        if (ucStation.TestStation.TestInfo.EnabledStartButton)
                        {
                            ucStation.OnStartTestResultChanged -= UcStation_OnStartTestResultChanged;
                            ucStation.OnStartTestResultChanged += UcStation_OnStartTestResultChanged;

                            ucStation.OnPowerOFFTestResultChanged -= UcStation_OnPowerOFFTestResultChanged;
                            ucStation.OnPowerOFFTestResultChanged += UcStation_OnPowerOFFTestResultChanged;

                            if (testStation.TestInfo.StationName == "AOI#1")
                            {
                                Barcode = "1_AOI" + this.GetRandom(10000, 99999).ToString();
                                Console.WriteLine("AOI#1########################################Barcode：" + Barcode);

                            }
                            if (testStation.TestInfo.StationName == "AOI#2")
                            {
                                Barcode = "2_AOI" + this.GetRandom(10000, 99999).ToString();
                                Console.WriteLine("AOI#2########################################Barcode：" + Barcode);

                            }
                            if (testStation.TestInfo.StationName == "AC#1")
                            {
                                Barcode = "1_AC" + this.GetRandom(10000, 99999).ToString();
                                Console.WriteLine("AC#1########################################Barcode：" + Barcode);

                            }
                            if (testStation.TestInfo.StationName == "AC#2")
                            {
                                Barcode = "2_AC" + this.GetRandom(10000, 99999).ToString();
                                Console.WriteLine("AC#2########################################Barcode：" + Barcode);

                            }

                            LogHelper.Info("0#####>>>[" + Barcode.ToString() + "]");
                            testStation.TestInfo.Barcode = Barcode.ToString().Trim().Replace("\n", "").Replace("\r", "");

                            //if (StationName.Contains("NTC"))
                            //{
                            //ucStation.OnScanBarcodeChanged -= UcStation_OnScanBarcodeChanged;
                            //ucStation.OnScanBarcodeChanged += UcStation_OnScanBarcodeChanged;
                            //}

                            ucStation.StartTest();
                        }
                        else
                        {
                            this.ShowPromptWindow("请确认设备是否连接？", PromptType.Red);
                        }
                    }
                }
            }
        }

        private void PowerOFFTest(string StationName)
        {
            foreach (TestStation testStation in ViewModel.TestStations)
            {
                int index = ViewModel.TestStations.IndexOf(testStation);

                var dependObj = itemsStation.ItemContainerGenerator.ContainerFromIndex(index);

                var ucStation = WPFHelper.FindVisualChildItem<UserControls.UcTestStation>(dependObj, "ucTestStationName");

                if (ucStation != null && ucStation.TestStation != null && ucStation.TestStation.TestInfo != null && ucStation.TestStation.TestInfo.StationName != null)
                {
                    ucStation.IsMultiStationStart = false;

                    if (ucStation.TestStation.TestInfo.StationName.Contains(StationName))
                    {
                        if (ucStation.TestStation.IsStop)
                        {
                            //ucStation.TestStation.IsPowerOFF = true;
                            ucStation.PowerOFFLed();
                            ucStation.OnStartTestResultChanged -= UcStation_OnStartTestResultChanged;
                            ucStation.OnPowerOFFTestResultChanged -= UcStation_OnPowerOFFTestResultChanged;
                            //ucStation.OnScanBarcodeChanged -= UcStation_OnScanBarcodeChanged;
                        }
                        else
                        {
                            LogHelper.Info(StationName + " IsStop:" + ucStation.TestStation.IsStop.ToString());
                        }
                    }
                }
            }
        }

        #endregion

        #region 点灯 关灯 回调函数
        //扫码
        private void UcStation_OnScanBarcodeChanged(TestStation testStation)
        {
            //if (testStation.TestInfo.StationName == "NTC#1")
            //{
            //    int Barcode = this.GetRandom(1000, 9999);
            //    Console.WriteLine("NTC#1########################################Barcode：" + Barcode);
               
            //    testStation.TestInfo.Barcode = Barcode.ToString();

            //    if (honeyWell3320Helper1 != null && honeyWell3320Helper1.IsConnected)
            //    {
            //        string NtcBarcode1 = honeyWell3320Helper1.OpenScanBarcode();
            //        honeyWell3320Helper1.CloseScanBarcode();

            //        testStation.TestInfo.Barcode = NtcBarcode1.ToString();
            //    }
            //}

            //if (testStation.TestInfo.StationName == "NTC#2")
            //{
            //    int Barcode = this.GetRandom(100, 999);
            //    Console.WriteLine("NTC#2########################################Barcode：" + Barcode);
                
            //    testStation.TestInfo.Barcode = Barcode.ToString();
            //    if (honeyWell3320Helper2 != null && honeyWell3320Helper2.IsConnected)
            //    {
            //        string NtcBarcode2 = honeyWell3320Helper2.OpenScanBarcode();
            //        honeyWell3320Helper2.CloseScanBarcode();

            //        testStation.TestInfo.Barcode = NtcBarcode2.ToString();
            //    }
            //}

            if (testStation.TestInfo.StationName == "AOI#1")
            {
                int Barcode = this.GetRandom(10000, 99999);
                Console.WriteLine("AOI#1########################################Barcode：" + Barcode);

                testStation.TestInfo.Barcode ="1_AOI" + Barcode.ToString();
            }
            if (testStation.TestInfo.StationName == "AOI#2")
            {
                int Barcode = this.GetRandom(10000, 99999);
                Console.WriteLine("AOI#2########################################Barcode：" + Barcode);

                testStation.TestInfo.Barcode = "2_AOI" + Barcode.ToString();
            }
            if (testStation.TestInfo.StationName == "AC#1")
            {
                int Barcode = this.GetRandom(10000, 99999);
                Console.WriteLine("AC#1########################################Barcode：" + Barcode);

                testStation.TestInfo.Barcode = "1_AC" + Barcode.ToString();
            }
            if (testStation.TestInfo.StationName == "AC#2")
            {
                int Barcode = this.GetRandom(10000, 99999);
                Console.WriteLine("AC#2########################################Barcode：" + Barcode);

                testStation.TestInfo.Barcode = "2_AC" + Barcode.ToString();
            }
        }

        //点灯成功或失败PC--->PLC
        private void UcStation_OnStartTestResultChanged(TestStation testStation, string Result)
        {

            Console.WriteLine($"StartTest%%%%%%%%%%{testStation.ConfigInfo.TestConfig.Station}%%%%%%%%%%%%%%%{Result}");
            if (testStation != null)
            {
                switch (testStation.ConfigInfo.TestConfig.Station)
                {
                    case "AOI#1":
                        {
                            Console.WriteLine($"AOI#1:%%%%%%%%%%{testStation.ConfigInfo.TestConfig.Station}%%%%%%%%%%%%%%%{Result}");
                            if (Result.ToUpper() == "TRUE") {

                                
                                PCToPLCSend(ViewModel.WriteAOIAddress1, new int[] { 1 });
                                
                                Console.WriteLine("AOI#1-Barcode:" + testStation.TestInfo.Barcode + "##Result:" + testStation.TestInfo.Result.ToString());

                                foreach (var itemResult in testStation.TestInfo.TestItemResults)
                                {
                                    if (itemResult.IsTest)
                                    {
                                        Console.WriteLine("AOI#1-Result:" + itemResult.Name + "##" + itemResult.Result + "##" + itemResult.ResultValue);
                                    }
                                }
                            }
                            else
                            {
                               
                                PCToPLCSend(ViewModel.WriteAOIAddress1, new int[] { -1 });
                                
                            }
                        }
                        break;
                    case "AOI#2":
                        {
                            Console.WriteLine($"AOI#2:%%%%%%%%%%{testStation.ConfigInfo.TestConfig.Station}%%%%%%%%%%%%%%%{Result}");
                            if (Result.ToUpper() == "TRUE")
                            {
                                PCToPLCSend(ViewModel.WriteAOIAddress2, new int[] { 1 });
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteAOIAddress2, new int[] { -1 });
                            }
                        }
                        break;
                    case "AC#1":
                        {
                            Console.WriteLine($"AC#1:%%%%%%%%%%{testStation.ConfigInfo.TestConfig.Station}%%%%%%%%%%%%%%%{Result}");
                            if (Result.ToUpper() == "TRUE")
                            {
                                PCToPLCSend(ViewModel.WriteACAddress1, new int[] { 1 });
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteACAddress1, new int[] { -1 });
                            }
                        }
                        break;
                    case "AC#2":
                        {
                            Console.WriteLine($"AC#2:%%%%%%%%%%{testStation.ConfigInfo.TestConfig.Station}%%%%%%%%%%%%%%%{Result}");
                            if (Result.ToUpper() == "TRUE")
                            {
                                PCToPLCSend(ViewModel.WriteACAddress2, new int[] { 1 });
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteACAddress2, new int[] { -1 });
                            }
                        }
                        break;
                    case "NTC#1":
                        {
                            Console.WriteLine($"NTC#1:%%%%%%%%%%{testStation.ConfigInfo.TestConfig.Station}%%%%%%%%%%%%%%%{Result}");
                            if (Result.ToUpper() == "TRUE")
                            {
                                PCToPLCSend(ViewModel.WriteNTCAddress1, new int[] { 1 });
                                //过站
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteNTCAddress1, new int[] { -1 });
                            }
                        }
                        break;
                    case "NTC#2":
                        {
                            Console.WriteLine($"NTC#2:%%%%%%%%%%{testStation.ConfigInfo.TestConfig.Station}%%%%%%%%%%%%%%%{Result}");
                            if (Result.ToUpper() == "TRUE")
                            {
                                PCToPLCSend(ViewModel.WriteNTCAddress2, new int[] { 1 });
                                //过站
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteNTCAddress2, new int[] { -1 });
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        //关灯成功或失败PC--->PLC
        private void UcStation_OnPowerOFFTestResultChanged(TestStation testStation, string PowerOFFResult)
        {
            Console.WriteLine($"PowerOFF%%%%%%%%%%{testStation.ConfigInfo.TestConfig.Station}%%%%%%%%%%%%%%%{PowerOFFResult}");
            if (testStation != null)
            {
                switch (testStation.ConfigInfo.TestConfig.Station)
                {
                    case "AOI#1":
                        {
                           
                            if (PowerOFFResult.ToUpper() == "PASS")
                            {

                                PCToPLCSend(ViewModel.WriteAOIAddress1, new int[] { 2 });
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteAOIAddress1, new int[] { -2 });
                            }
                        }
                        break;
                    case "AOI#2":
                        {
                            
                            if (PowerOFFResult.ToUpper() == "PASS")
                            {
                                PCToPLCSend(ViewModel.WriteAOIAddress2, new int[] { 2 });
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteAOIAddress2, new int[] { -2 });
                            }
                        }
                        break;
                    case "AC#1":
                        {
                          
                            if (PowerOFFResult.ToUpper() == "PASS")
                            {
                                PCToPLCSend(ViewModel.WriteACAddress1, new int[] { 2 });
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteACAddress1, new int[] { -2 });
                            }
                        }
                        break;
                    case "AC#2":
                        {
                           
                            if (PowerOFFResult.ToUpper() == "PASS")
                            {
                                PCToPLCSend(ViewModel.WriteACAddress2, new int[] { 2 });
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteACAddress2, new int[] { -2 });
                            }
                        }
                        break;
                    case "NTC#1":
                        {
                           
                            if (PowerOFFResult.ToUpper() == "PASS")
                            {
                                PCToPLCSend(ViewModel.WriteNTCPowerOffAddress1, new int[] { 2 });
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteNTCPowerOffAddress1, new int[] { -2 });
                            }
                        }
                        break;
                    case "NTC#2":
                        {
                           
                            if (PowerOFFResult.ToUpper() == "PASS")
                            {
                                PCToPLCSend(ViewModel.WriteNTCPowerOffAddress2, new int[] { 2 });
                            }
                            else
                            {
                                PCToPLCSend(ViewModel.WriteNTCPowerOffAddress2, new int[] { -2 });
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        #endregion

        #region OnPLCClick
        private void OnPLCClick(object parameter)
        {
            if (parameter != null)
            {
                switch (parameter.ToString())
                {
                    case "ClearLog":
                        {
                            this.rtxtPLCTestData.Document.Blocks.Clear();
                        }
                        break;
                    case "LinkPLC":
                        {
                            //m_MelsecPLCHelper = new MelsecPLCHelper(ViewModel.PLC_IPName, ViewModel.PLC_PortName);
                            //await m_MelsecPLCHelper.Open();
                            this.Loading.Show("Link PLC ...");
                            Task.Factory.StartNew(() =>
                            {
                                this.OpenPLC();

                            }).ContinueWith(t =>
                            {
                                this.Loading.Hide();
                            });
                            
                        }
                        break;
                    case "DisLinkPLC":
                        {
                            if (ViewModel.IsPLCConnect)
                            {
                                m_MelsecPLCHelper.Close();
                                
                                m_MelsecPLCHelper = null;

                                ViewModel.IsPLCConnect = false;

                                if (cts != null && task != null)
                                {
                                    Console.WriteLine("%%%%%%%%%%%%%%%%%%%%%%%%%%5");
                                    
                                    cts.Cancel();

                                    //Task.WaitAll(new Task[] { task });

                                }
                                //cts1.Cancel(); cts2.Cancel(); cts3.Cancel(); cts4.Cancel(); cts5.Cancel(); cts6.Cancel();
                                //Task.WaitAll(new Task[] { task1, task2, task3, task4, task5, task6 });
                            }
                        }
                        break;
                    case "AOI#1PCToPLCLightOK":
                        {
                            PCToPLCSend(ViewModel.WriteAOIAddress1, new int[] { 1 });
                        }
                        break;
                    case "AOI#1PCToPLCLightNG":
                        {
                            PCToPLCSend(ViewModel.WriteAOIAddress1, new int[] { -1 });
                        }
                        break;
                    case "AOI#1PCToPLCCloseOK":
                        {
                            PCToPLCSend(ViewModel.WriteAOIAddress1, new int[] { 2 });
                        }
                        break;
                    case "AOI#1PCToPLCCloseNG":
                        {
                            PCToPLCSend(ViewModel.WriteAOIAddress1, new int[] { -2 });
                        }
                        break;
                    case "AOI#2PCToPLCLightOK":
                        {
                            PCToPLCSend(ViewModel.WriteAOIAddress2, new int[] { 1 });
                        }
                        break;
                    case "AOI#2PCToPLCLightNG":
                        {
                            PCToPLCSend(ViewModel.WriteAOIAddress2, new int[] { -1 });
                        }
                        break;
                    case "AOI#2PCToPLCCloseOK":
                        {
                            PCToPLCSend(ViewModel.WriteAOIAddress2, new int[] { 2 });
                        }
                        break;
                    case "AOI#2PCToPLCCloseNG":
                        {
                            PCToPLCSend(ViewModel.WriteAOIAddress2, new int[] { -2 });
                        }
                        break;
                    case "AC#1PCToPLCLightOK":
                        {
                            PCToPLCSend(ViewModel.WriteACAddress1, new int[] { 1 });
                        }
                        break;
                    case "AC#1PCToPLCLightNG":
                        {
                            PCToPLCSend(ViewModel.WriteACAddress1, new int[] { -1 });
                        }
                        break;
                    case "AC#1PCToPLCCloseOK":
                        {
                            PCToPLCSend(ViewModel.WriteACAddress1, new int[] { 2 });
                        }
                        break;
                    case "AC#1PCToPLCCloseNG":
                        {
                            PCToPLCSend(ViewModel.WriteACAddress1, new int[] { -2 });
                        }
                        break;
                    case "AC#2PCToPLCLightOK":
                        {
                            PCToPLCSend(ViewModel.WriteACAddress2, new int[] { 1 });
                        }
                        break;
                    case "AC#2PCToPLCLightNG":
                        {
                            PCToPLCSend(ViewModel.WriteACAddress2, new int[] { -1 });
                        }
                        break;
                    case "AC#2PCToPLCCloseOK":
                        {
                            PCToPLCSend(ViewModel.WriteACAddress2, new int[] { 2 });
                        }
                        break;
                    case "AC#2PCToPLCCloseNG":
                        {
                            PCToPLCSend(ViewModel.WriteACAddress2, new int[] { -2 });
                        }
                        break;
                    case "NTC#1PCToPLCLightOK":
                        {
                            PCToPLCSend(ViewModel.WriteNTCAddress1, new int[] { 1 });
                        }
                        break;
                    case "NTC#1PCToPLCLightNG":
                        {
                            PCToPLCSend(ViewModel.WriteNTCAddress1, new int[] { -1 });
                        }
                        break;
                    case "NTC#1PCToPLCCloseOK":
                        {
                            PCToPLCSend(ViewModel.WriteNTCPowerOffAddress1, new int[] { 2 });
                        }
                        break;
                    case "NTC#1PCToPLCCloseNG":
                        {
                            PCToPLCSend(ViewModel.WriteNTCPowerOffAddress1, new int[] { -2 });
                        }
                        break;
                    case "NTC#2PCToPLCLightOK":
                        {
                            PCToPLCSend(ViewModel.WriteNTCAddress2, new int[] { 1 });
                        }
                        break;
                    case "NTC#2PCToPLCLightNG":
                        {
                            PCToPLCSend(ViewModel.WriteNTCAddress2, new int[] { -1 });
                        }
                        break;
                    case "NTC#2PCToPLCCloseOK":
                        {
                            PCToPLCSend(ViewModel.WriteNTCPowerOffAddress2, new int[] { 2 });
                        }
                        break;
                    case "NTC#2PCToPLCCloseNG":
                        {
                            PCToPLCSend(ViewModel.WriteNTCPowerOffAddress2, new int[] { -2 });
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        #endregion

        #region ChangePage
        private Grid CurrentShowGrid { get; set; }

        private void ChangePage(Grid grid)
        {
            if (grid == this.CurrentShowGrid)
            {
                return;
            }
            else
            {

                if (grid == this.GridOperator)
                {

                }

                this.CurrentShowGrid.Hide(Bandit.UI.Animation.Scale | Bandit.UI.Animation.Opacity, 0.5, delegate
                {
                    this.CurrentShowGrid = grid;

                    grid.Show(Bandit.UI.Animation.Scale | Bandit.UI.Animation.Opacity, 0.5);
                });
            }

        }
        #endregion

        #region 当设备连接或断开后更新开始测试按钮的状态
        private void UpdateStartButtonState()
        {
            ViewModel.TestInfo.EnabledStartButton = true; //RelayBoardHelper.RelayBoards.All(s => s.IsConnect) && this._Meter.IsConnected;

            if (ViewModel.TestInfo.EnabledStartButton)
            {
                ViewModel.Status.Update("Ready", MyBrushes.RichBlue);
            }
            else
            {
                ViewModel.Status.Update("Wating...", MyBrushes.RichRed);
            }
        }
        #endregion

        #region New Station
        private void ShowStationEdiePanel()
        {
            this.ucPanelStationAdd.Show(0.3, delegate
            {
                this.txtStationName.Focus();
            });
        }

        private void HideStationEditPanel()
        {
            this.ucPanelStationAdd.Hide(0.3, delegate
            {
                this.txtStationName.Clear();
            });
        }

        private void AddStation()
        {
            if (string.IsNullOrWhiteSpace(this.txtStationName.Text))
            {
                this.ShowDialogByPlease("Please input station name.");
                this.txtStationName.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(ViewModel.PortName))
            {
                this.ShowDialogByPlease("Please Select PortName.");

                return;
            }

            if (ViewModel.PortName != "Com999")
            {
                if (App.DLEDLightingHelpers.Where(s => s.PortName == ViewModel.PortName).Count() > 0)
                {
                    //判断一下选择 的Com号是否已经选过了。
                    this.ShowDialogByPlease("Please Select Other PortName,this is Exist");

                    return;

                }
            }
            try
            {
                int currentCount = ViewModel.StationCount;

                this.ViewModel.AddStation(new TestStation(new Models.StationInfo(this.txtStationName.Text, ViewModel.PortName, currentCount++)));

                this.HideStationEditPanel();
            }
            catch (Exception ex)
            {
                Bandit.Helpers.LogHelper.Error(ex, "AddStation");
                this.ShowDialog(ex.Message, "Error", MessageBoxButton.OK, DialogIcon.Error);
            }
        }

        #endregion

        #region 固件升级
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mi = sender as MenuItem;

            OnClick(mi.Tag);
        }

        #region 刷新Tetra
        private void Refresh()
        {
            if (this.lbTetraItems.SelectedItem is Tetra item)
            {
                //Console.WriteLine(item.ToString());
                //连接
                this.Loading.Show();
                this.SwitchTetra(item, delegate
                {
                    this.Loading.Hide();
                });
            }
        }
        #endregion

        #region 添加Tetra
        private void AddTetra()
        {
            this.ViewModel.TetraModel = new Tetra("", "", "");

            this.IsAdding = true;

            this.btnOKAndContinue.Visibility = System.Windows.Visibility.Visible;

            this.ucPanelEditTetra.Show(0.3, (Action)delegate { this.txtAddress.Focus(); });

        }
        #endregion

        #region 编辑Tetra
        private void EditTetra()
        {
            this.IsAdding = false;

            this.btnOKAndContinue.Visibility = System.Windows.Visibility.Collapsed;

            this.ucPanelEditTetra.Show(0.3, (Action)delegate { this.txtAddress.Focus(); });

        }
        #endregion

        #region 删除Tetra
        private void DeleteTetra()
        {
            if (BanditDialog.Show("确定删除", "删除提示", MessageBoxButton.OKCancel, DialogIcon.QuestionFace) == MessageBoxResult.OK)
            {
                this.Loading.Show();

                JsonConfig.Instance.TetraItems.Remove(this.lbTetraItems.SelectedItem as Tetra);

                Task.Factory.StartNew(() =>
                {

                    JsonConfig.SaveJsonConfig();

                    JsonConfig.LoadJsonConfig();

                    ViewModel.JsonConfig = JsonConfig.Instance;

                }).ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.lbTetraItems.ItemsSource = null;
                        this.lbTetraItems.ItemsSource = ViewModel.JsonConfig.TetraItems;

                        this.Loading.Hide();
                    }));
                });

            }
        }

        #endregion

        private string RemoteTestLogPath = "TestLog";

        #region Tetra切换
        private void SwitchTetra(Tetra item, Action complete)
        {
            this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

            Task.Factory.StartNew(delegate
            {
                foreach (Tetra tetra in JsonConfig.Instance.TetraItems)
                {
                    tetra.State = false;
                }

                this.ViewModel.ConfigFileModels = new List<ConfigFileModel>();
                this.ViewModel.RemoteTestLogModels = new ObservableCollection<TetraTestLogModel>();

                _Tetra = new TetraController(item);

                AppendUpgradeProgramLog($"正在连接PI主机:{item.Address}", MyBrushes.RichGreen);

                if (_Tetra.Connect())
                {
                    //this.Refresh();
                    RemoveLastBlockAppendLog();

                    this.ViewModel.ConfigFileModels = _Tetra.GetRemoteConfigFile("Configs", ".tcg");
                    this.ViewModel.RemoteTestLogModels = _Tetra.GetRemoteTestLogFile("TestLog");

                    RemoteTestLogPath = "TestLog";
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        ucTestLogName.Title = RemoteTestLogPath;
                    }));
                    this.ShowPromptWindow($"连接PI主机:{item.Address} 成功", Bandit.UI.PromptType.Green, 1);

                    AppendUpgradeProgramLog($"连接PI主机:{item.Address} 成功", MyBrushes.RichGreen);

                    item.State = true;
                }
                else
                {
                    RemoveLastBlockAppendLog();

                    this.ShowPromptWindow("未能连接PI主机,请确认其是否在线", Bandit.UI.PromptType.Red, 2);

                    AppendUpgradeProgramLog($"连接PI主机:{item.Address} 失败", MyBrushes.RichRed);
                }
            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    task.LogExceptions();
                }

                this.Dispatcher.Invoke(new Action(() =>
                {
                    this.lbRemoteConfigFileItems.ItemsSource = null;
                    this.lbRemoteConfigFileItems.ItemsSource = this.ViewModel.ConfigFileModels;

                    this.lbRemoteTestLogItems.ItemsSource = null;
                    this.lbRemoteTestLogItems.ItemsSource = this.ViewModel.RemoteTestLogModels;
                }));

                complete.Invoke();

            });
        }

        #endregion

        #region DownloadPITestLog
        private void DownloadPITestLog()
        {
            if (_Tetra == null || !_Tetra.Model.State)
            {
                this.ShowDialog("PI尚未连接", App.PromptText, MessageBoxButton.OK, Bandit.UI.DialogIcon.Information);
                return;
            }
            this.Loading.Show("正在下载Log。。。");

            Task.Factory.StartNew(delegate
            {

                //_Tetra.DownloadLog(localPath, "TestLog");
                string localPath = this.GetBaseDirectory() + "PGTestLog" + $"\\{_Tetra.Address}";

                foreach (TetraTestLogModel tetraTestLogModel in this.ViewModel.RemoteTestLogModels)
                {
                    if (tetraTestLogModel.IsDownLoad)
                    {
                        if (tetraTestLogModel.IsFile)
                        {
                            string localFilePath = this.GetBaseDirectory() + "PGTestLog" + $"\\{_Tetra.Address}" + "\\" + tetraTestLogModel.FileName.Substring("/home/pi/Desktop/TestLog/".Length).Replace('/', '\\');
                            _Tetra.DownloadTestLogFile(localFilePath, tetraTestLogModel.FileName);
                        }
                        else
                        {
                            localPath += "\\" + tetraTestLogModel.FileName.Substring("/home/pi/Desktop/TestLog/".Length).Replace('/', '\\');

                            _Tetra.DownloadTestLogDirectory(localPath, tetraTestLogModel.FileName);
                        }

                    }

                }

                System.Diagnostics.Process.Start(localPath);

            }).ContinueWith(task =>
            {
                this.Loading.Hide();
                task.LogExceptions("DownloadPGTestLog");
            });

        }
        #endregion

        #region DownloadPILog
        private void DownloadPILog()
        {
            if (_Tetra == null || !_Tetra.Model.State)
            {
                this.ShowDialog("PI尚未连接", App.PromptText, MessageBoxButton.OK, Bandit.UI.DialogIcon.Information);
                return;
            }

            this.Loading.Show("正在下载Log。。。");

            Task.Factory.StartNew(delegate
            {
                string localPath = this.GetBaseDirectory() + "PGLog" + $"\\{_Tetra.Address}";

                _Tetra.DownloadLog(localPath, "Log");

                System.Diagnostics.Process.Start(localPath);

            }).ContinueWith(task =>
            {
                this.Loading.Hide();
                task.LogExceptions("DownloadPGLog");
            });
        }
        #endregion

        #region 升级
        private void Upgrade()
        {
            string programFile = this.txtProgramFile.Text;

            if (string.IsNullOrWhiteSpace(programFile))
            {
                this.ShowDialog("请选择要升级的程序文件", App.PromptText, MessageBoxButton.OK, Bandit.UI.DialogIcon.Information);
                return;
            }

            this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

            this.Loading.Show("正在升级...");

            this.btnUpgrade.IsEnabled = false;

            Task.Factory.StartNew(delegate
            {
                if (!_Tetra.Model.State)
                {
                    this.AppendUpgradeProgramLog("检测连接已断开，正在重连中......", MyBrushes.RichBlue);
                    if (_Tetra.Connect())
                    {
                        this.RemoveLastBlockAppendLog();
                        this.AppendUpgradeProgramLog("点灯机[Host]连接成功！".Replace("Host", _Tetra.Address), MyBrushes.RichGreen);
                    }
                    else
                    {
                        this.RemoveLastBlockAppendLog();
                        this.AppendUpgradeProgramLog("点灯机[Host]连接失败！".Replace("Host", _Tetra.Address), MyBrushes.RichRed);
                        return;
                    }
                }

                this.AppendUpgradeProgramLog("开始升级", MyBrushes.RichGreen);

                _Tetra.UpgradeProgram(programFile, (state) =>
                {
                    MyBrushes brush = MyBrushes.White;

                    string str = state.ToString();

                    if (str.EndsWith("Success") || str.EndsWith("Complete"))
                    {
                        brush = MyBrushes.RichGreen;
                    }
                    else if (str.EndsWith("Fail"))
                    {
                        brush = MyBrushes.RichRed;
                    }

                    this.AppendUpgradeProgramLog(App.GetString(str), brush);

                });
            }).ContinueWith(task =>
            {
                this.ThreadSafe(delegate
                {
                    this.btnUpgrade.IsEnabled = true;
                    this.Loading.Hide();

                });
            });
        }

        private void AllUpgrade()
        {
            string programFile = this.txtProgramFile.Text;

            if (string.IsNullOrWhiteSpace(programFile))
            {
                this.ShowDialog("请选择要升级的程序文件", App.PromptText, MessageBoxButton.OK, Bandit.UI.DialogIcon.Information);
                return;
            }

            this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

            this.Loading.Show("正在升级...");

            Task.Factory.StartNew(delegate
            {

                foreach (Tetra tetra in JsonConfig.Instance.TetraItems)
                {
                    if (tetra == null || !tetra.IsSelected)
                    {
                        continue;
                    }

                    tetra.State = false;

                    _Tetra = new TetraController(tetra);

                    AppendUpgradeProgramLog($"正在连接PI主机:{tetra.Address}", MyBrushes.RichGreen);

                    if (_Tetra.Connect())
                    {
                        //this.Refresh();
                        //this.ViewModel.ConfigFileModels = _Tetra.GetRemoteConfigFile("Configs", ".xml");
                        RemoveLastBlockAppendLog();

                        this.ShowPromptWindow($"连接PI主机:{tetra.Address} 成功", Bandit.UI.PromptType.Green, 1);

                        AppendUpgradeProgramLog($"连接PI主机:{tetra.Address} 成功", MyBrushes.RichGreen);

                        tetra.State = true;
                    }
                    else
                    {
                        RemoveLastBlockAppendLog();

                        this.ShowPromptWindow("未能连接PI主机,请确认其是否在线", Bandit.UI.PromptType.Red, 2);

                        AppendUpgradeProgramLog($"连接PI主机:{tetra.Address} 失败", MyBrushes.RichRed);

                        continue;
                    }

                    this.AppendUpgradeProgramLog("开始升级", MyBrushes.RichGreen);

                    _Tetra.UpgradeProgram(programFile, (state) =>
                    {
                        MyBrushes brush = MyBrushes.White;

                        string str = state.ToString();

                        if (str.EndsWith("Success") || str.EndsWith("Complete"))
                        {
                            brush = MyBrushes.RichGreen;
                        }
                        else if (str.EndsWith("Fail"))
                        {
                            brush = MyBrushes.RichRed;
                        }

                        this.AppendUpgradeProgramLog(App.GetString(str), brush);

                    });
                }

            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    task.LogExceptions();
                }


                this.Dispatcher.Invoke(new Action(() =>
                {
                    this.Loading.Hide();
                    //this.lbRemoteConfigFileItems.ItemsSource = null;
                    //this.lbRemoteConfigFileItems.ItemsSource = this.ViewModel.ConfigFileModels;
                }));

            });

        }

        #endregion

        #region UpdateConfigFile
        private void UpdateConfigFile()
        {
            //string programFile = this.tbTcgDirtoryName.Text;

            if (ViewModel.TetraTcgFileInfoList.Count == 0)
            {
                this.ShowDialog("请选择存在tcg文件的目录", App.PromptText, MessageBoxButton.OK, Bandit.UI.DialogIcon.Information);
                return;
            }

            if (ViewModel.TetraTcgFileInfoList.Where(s => s.IsUpdata == true).Count() == 0)
            {
                this.ShowDialog("请选择要上传的tcg文件", App.PromptText, MessageBoxButton.OK, Bandit.UI.DialogIcon.Information);
                return;
            }

            this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

            this.btnUpDateConfigFile.IsEnabled = false;

            this.Loading.Show();

            Task.Factory.StartNew(delegate
            {
                if (!_Tetra.Model.State)
                {
                    this.AppendUpgradeProgramLog("检测连接已断开，正在重连中......", MyBrushes.RichBlue);

                    if (_Tetra.Connect())
                    {
                        this.RemoveLastBlockAppendLog();
                        this.AppendUpgradeProgramLog("点灯机[Host]连接成功！".Replace("Host", _Tetra.Address), MyBrushes.RichGreen);
                    }
                    else
                    {
                        this.RemoveLastBlockAppendLog();
                        this.AppendUpgradeProgramLog("点灯机[Host]连接失败！".Replace("Host", _Tetra.Address), MyBrushes.RichRed);
                        return;
                    }
                }

                foreach (TetraTcgFileInfo tetraTcgFileInfo in ViewModel.TetraTcgFileInfoList)
                {
                    if (tetraTcgFileInfo.IsUpdata)
                    {

                        AppendUpgradeProgramLog($"正在上传:{tetraTcgFileInfo.Name}.tcg...", MyBrushes.RichGreen);

                        if (_Tetra.UpdateConfigFile(tetraTcgFileInfo.FilePath, "Configs"))
                        {
                            this.AppendUpgradeProgramLog($"{tetraTcgFileInfo.FilePath}上传成功", MyBrushes.RichGreen);

                            this.ViewModel.ConfigFileModels = _Tetra.GetRemoteConfigFile("Configs", ".tcg");
                        }
                        else
                        {
                            this.AppendUpgradeProgramLog($"{tetraTcgFileInfo.FilePath}上传失败", MyBrushes.RichRed);
                        }
                    }
                }

            }).ContinueWith(task =>
            {
                this.ThreadSafe(delegate
                {
                    this.btnUpDateConfigFile.IsEnabled = true;

                    this.lbRemoteConfigFileItems.ItemsSource = null;
                    this.lbRemoteConfigFileItems.ItemsSource = this.ViewModel.ConfigFileModels;

                    this.Loading.Hide();
                });
            });

        }

        private void UpdateConfigFileToAllDevice()
        {
            if (ViewModel.TetraTcgFileInfoList.Count == 0)
            {
                this.ShowDialog("请选择存在tcg文件的目录", App.PromptText, MessageBoxButton.OK, Bandit.UI.DialogIcon.Information);
                return;
            }

            if (ViewModel.TetraTcgFileInfoList.Where(s => s.IsUpdata == true).Count() == 0)
            {
                this.ShowDialog("请选择要上传的tcg文件", App.PromptText, MessageBoxButton.OK, Bandit.UI.DialogIcon.Information);
                return;
            }

            this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

            this.Loading.Show();

            Task.Factory.StartNew(delegate
            {

                foreach (Tetra tetra in JsonConfig.Instance.TetraItems)
                {
                    if (tetra == null || !tetra.IsSelected)
                    {
                        continue;
                    }

                    tetra.State = false;

                    _Tetra = new TetraController(tetra);

                    AppendUpgradeProgramLog($"正在连接PI主机:{tetra.Address}", MyBrushes.RichGreen);

                    if (_Tetra.Connect())
                    {
                        //this.Refresh();
                        //this.ViewModel.ConfigFileModels = _Tetra.GetRemoteConfigFile("Configs", ".xml");
                        RemoveLastBlockAppendLog();

                        this.ShowPromptWindow($"连接PI主机:{tetra.Address} 成功", Bandit.UI.PromptType.Green, 1);

                        AppendUpgradeProgramLog($"连接PI主机:{tetra.Address} 成功", MyBrushes.RichGreen);

                        tetra.State = true;
                    }
                    else
                    {
                        RemoveLastBlockAppendLog();

                        this.ShowPromptWindow("未能连接PI主机,请确认其是否在线", Bandit.UI.PromptType.Red, 2);

                        AppendUpgradeProgramLog($"连接PI主机:{tetra.Address} 失败", MyBrushes.RichRed);

                        continue;
                    }

                    foreach (TetraTcgFileInfo tetraTcgFileInfo in ViewModel.TetraTcgFileInfoList)
                    {
                        if (tetraTcgFileInfo.IsUpdata)
                        {
                            AppendUpgradeProgramLog($"正在上传:{tetraTcgFileInfo.Name}.tcg...", MyBrushes.RichGreen);

                            if (_Tetra.UpdateConfigFile(tetraTcgFileInfo.FilePath, "Configs"))
                            {
                                this.AppendUpgradeProgramLog($"{tetraTcgFileInfo.FilePath}上传成功", MyBrushes.RichGreen);

                                this.ViewModel.ConfigFileModels = _Tetra.GetRemoteConfigFile("Configs", ".tcg");
                            }
                            else
                            {
                                this.AppendUpgradeProgramLog($"{tetraTcgFileInfo.FilePath}上传失败", MyBrushes.RichRed);
                            }
                        }
                    }
                    //string localPathFile = "".GetBaseDirectory() + "TestConfigFiles\\" + programFile;

                    //if (_Tetra.UpdateConfigFile(localPathFile, "Configs"))
                    //{
                    //    this.AppendUpgradeProgramLog($"{tetra.Address}:{programFile}上传成功", MyBrushes.RichGreen);

                    //    //this.ViewModel.ConfigFileModels = _Tetra.GetRemoteConfigFile("Configs", ".xml");
                    //}
                    //else
                    //{
                    //    this.AppendUpgradeProgramLog($"{tetra.Address}:{programFile}上传失败", MyBrushes.RichRed);
                    //}
                }

            }).ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    task.LogExceptions();
                }


                this.Dispatcher.Invoke(new Action(() =>
                {
                    this.Loading.Hide();
                    //this.lbRemoteConfigFileItems.ItemsSource = null;
                    //this.lbRemoteConfigFileItems.ItemsSource = this.ViewModel.ConfigFileModels;
                }));

            });

        }

        #endregion

        #region DeleteConfigFile
        private void DeleteConfigFile()
        {
            if (BanditDialog.Show("确定删除", "删除提示", MessageBoxButton.OKCancel, DialogIcon.Question) == MessageBoxResult.OK)
            {
                this.Loading.Show();

                this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

                Task.Factory.StartNew(() =>
                {
                    if (!_Tetra.Model.State)
                    {
                        this.AppendUpgradeProgramLog("检测连接已断开，正在重连中......", MyBrushes.RichBlue);
                        if (_Tetra.Connect())
                        {
                            this.AppendUpgradeProgramLog("PG[Host]连接成功！".Replace("Host", _Tetra.Address), MyBrushes.RichGreen);
                        }
                        else
                        {
                            this.AppendUpgradeProgramLog("PG[Host]连接失败！".Replace("Host", _Tetra.Address), MyBrushes.RichRed);
                            return;
                        }
                    }

                    if (_Tetra.RemoveConfigFile(ViewModel.ConfigFileModel.FileName, "Configs"))
                    {
                        this.AppendUpgradeProgramLog($"{ViewModel.ConfigFileModel.FileName}删除成功", MyBrushes.RichGreen);
                        this.ViewModel.ConfigFileModels = _Tetra.GetRemoteConfigFile("Configs", ".tcg");
                    }
                    else
                    {
                        this.AppendUpgradeProgramLog($"{ViewModel.ConfigFileModel.FileName}删除失败", MyBrushes.RichRed);
                    }


                }).ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.lbRemoteConfigFileItems.ItemsSource = null;
                        this.lbRemoteConfigFileItems.ItemsSource = ViewModel.ConfigFileModels;

                        this.Loading.Hide();
                    }));
                });

            }
        }

        private void DeleteAllRemoteConfigsFile()
        {
            if (BanditDialog.Show("确定删除远程所有配置文件?", "删除提示", MessageBoxButton.OKCancel, DialogIcon.Question) == MessageBoxResult.OK)
            {
                this.Loading.Show();

                this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

                Task.Factory.StartNew(() =>
                {
                    if (!_Tetra.Model.State)
                    {
                        this.AppendUpgradeProgramLog("检测连接已断开，正在重连中......", MyBrushes.RichBlue);
                        if (_Tetra.Connect())
                        {
                            this.AppendUpgradeProgramLog("PG[Host]连接成功！".Replace("Host", _Tetra.Address), MyBrushes.RichGreen);
                        }
                        else
                        {
                            this.AppendUpgradeProgramLog("PG[Host]连接失败！".Replace("Host", _Tetra.Address), MyBrushes.RichRed);
                            return;
                        }
                    }

                    foreach (ConfigFileModel configFileModel in this.ViewModel.ConfigFileModels)
                    {

                        if (_Tetra.RemoveConfigFile(configFileModel.FileName, "Configs"))
                        {

                            this.AppendUpgradeProgramLog($"{configFileModel.FileName}删除成功", MyBrushes.RichGreen);

                        }
                        else
                        {
                            this.AppendUpgradeProgramLog($"{configFileModel.FileName}删除失败", MyBrushes.RichRed);
                        }
                    }

                    this.ViewModel.ConfigFileModels = _Tetra.GetRemoteConfigFile("Configs", ".tcg");

                }).ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.lbRemoteConfigFileItems.ItemsSource = null;
                        this.lbRemoteConfigFileItems.ItemsSource = ViewModel.ConfigFileModels;

                        this.Loading.Hide();
                    }));
                });

            }
        }

        #endregion

        #region DeleteTestLogFile
        private void DeleteTestLogFile()
        {
            if (BanditDialog.Show("确定删除", "删除提示", MessageBoxButton.OKCancel, DialogIcon.Question) == MessageBoxResult.OK)
            {
                this.Loading.Show();

                this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

                Task.Factory.StartNew(() =>
                {
                    if (!_Tetra.Model.State)
                    {
                        this.AppendUpgradeProgramLog("检测连接已断开，正在重连中......", MyBrushes.RichBlue);
                        if (_Tetra.Connect())
                        {
                            this.AppendUpgradeProgramLog("PG[Host]连接成功！".Replace("Host", _Tetra.Address), MyBrushes.RichGreen);
                        }
                        else
                        {
                            this.AppendUpgradeProgramLog("PG[Host]连接失败！".Replace("Host", _Tetra.Address), MyBrushes.RichRed);
                            return;
                        }
                    }

                    if (_Tetra.DeleteTestLogFile(ViewModel.TestLogFileModel.FileName))
                    {
                        this.AppendUpgradeProgramLog($"{ViewModel.TestLogFileModel.FileName}删除成功", MyBrushes.RichGreen);
                        this.ViewModel.RemoteTestLogModels = _Tetra.GetRemoteTestLogFile(RemoteTestLogPath);
                    }
                    else
                    {
                        this.AppendUpgradeProgramLog($"{ViewModel.TestLogFileModel.FileName}删除失败", MyBrushes.RichRed);
                    }


                }).ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.lbRemoteTestLogItems.ItemsSource = null;
                        this.lbRemoteTestLogItems.ItemsSource = ViewModel.RemoteTestLogModels;

                        this.Loading.Hide();
                    }));
                });

            }
        }

        private void DeleteTestLogDir()
        {
            if (BanditDialog.Show("确定删除所有TestLog吗?", "删除提示", MessageBoxButton.OKCancel, DialogIcon.Question) == MessageBoxResult.OK)
            {
                this.Loading.Show();

                this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

                Task.Factory.StartNew(() =>
                {
                    if (!_Tetra.Model.State)
                    {
                        this.AppendUpgradeProgramLog("检测连接已断开，正在重连中......", MyBrushes.RichBlue);
                        if (_Tetra.Connect())
                        {
                            this.AppendUpgradeProgramLog("PG[Host]连接成功！".Replace("Host", _Tetra.Address), MyBrushes.RichGreen);
                        }
                        else
                        {
                            this.AppendUpgradeProgramLog("PG[Host]连接失败！".Replace("Host", _Tetra.Address), MyBrushes.RichRed);
                            return;
                        }
                    }

                    if (_Tetra.DeleteTestLogDirectory())
                    {
                        this.AppendUpgradeProgramLog($"/home/pi/Desktop/TestLog/文件夹删除成功", MyBrushes.RichGreen);
                        RemoteTestLogPath = "TestLog";
                        this.ViewModel.RemoteTestLogModels = _Tetra.GetRemoteTestLogFile(RemoteTestLogPath);
                    }
                    else
                    {
                        this.AppendUpgradeProgramLog($"/home/pi/Desktop/TestLog/文件夹删除失败", MyBrushes.RichRed);
                    }


                }).ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        this.lbRemoteTestLogItems.ItemsSource = null;
                        this.lbRemoteTestLogItems.ItemsSource = ViewModel.RemoteTestLogModels;

                        this.Loading.Hide();
                    }));
                });

            }
        }

        private void DeleteLogDir()
        {
            if (BanditDialog.Show("确定删除所有交互Log吗?", "删除提示", MessageBoxButton.OKCancel, DialogIcon.Question) == MessageBoxResult.OK)
            {
                this.Loading.Show();

                this.rtxtUpgradeProgramLog.Document.Blocks.Clear();

                Task.Factory.StartNew(() =>
                {
                    if (!_Tetra.Model.State)
                    {
                        this.AppendUpgradeProgramLog("检测连接已断开，正在重连中......", MyBrushes.RichBlue);
                        if (_Tetra.Connect())
                        {
                            this.AppendUpgradeProgramLog("PG[Host]连接成功！".Replace("Host", _Tetra.Address), MyBrushes.RichGreen);
                        }
                        else
                        {
                            this.AppendUpgradeProgramLog("PG[Host]连接失败！".Replace("Host", _Tetra.Address), MyBrushes.RichRed);
                            return;
                        }
                    }

                    if (_Tetra.DeleteLogDirectory())
                    {
                        this.AppendUpgradeProgramLog($"/home/pi/Desktop/交互Log/文件夹删除成功", MyBrushes.RichGreen);

                    }
                    else
                    {
                        this.AppendUpgradeProgramLog($"/home/pi/Desktop/交互Log/文件夹删除失败", MyBrushes.RichRed);
                    }


                }).ContinueWith(t =>
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {

                        this.Loading.Hide();
                    }));
                });

            }
        }
        #endregion

        private void lbRemoteTestlogList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbRemoteTestLogItems.SelectedItem != null)
            {
                TetraTestLogModel tetraTestLogModel = lbRemoteTestLogItems.SelectedItem as TetraTestLogModel;

                if (tetraTestLogModel.IsFile)
                {
                    Console.WriteLine("testLog:" + tetraTestLogModel.FileName);
                    //ViewModel.TestLogFileModel.FileName= tetraTestLogModel.FileName;
                }
                else
                {
                    this.Dispatcher.Invoke(new Action(() =>
                    {
                        ucTestLogName.Title = tetraTestLogModel.FileName;
                    }));

                    RemoteTestLogPath = RemoteTestLogPath + "/" + tetraTestLogModel.Name;

                    this.ViewModel.RemoteTestLogModels = _Tetra.GetRemoteTestLogFile(RemoteTestLogPath);

                    this.lbRemoteTestLogItems.ItemsSource = null;
                    this.lbRemoteTestLogItems.ItemsSource = ViewModel.RemoteTestLogModels;
                }
            }
        }

        #endregion

        #region 追加测试数据UpgradeProgram

        private Block GetBlock(string data, MyBrushes statusBrush)
        {
            Inline inline = new Run(data);

            inline.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(statusBrush.ToBrushString()));

            return new Paragraph(inline) { LineHeight = 1.0 };
        }

        private Block AppendUpgradeProgramLog(string data, MyBrushes brush)
        {
            Block block = null;

            if (this.Dispatcher.Thread == System.Threading.Thread.CurrentThread)
            {
                block = GetBlock(data, brush);

                this.rtxtUpgradeProgramLog.Document.Blocks.Add(block);
            }
            else
            {
                this.Dispatcher.Invoke((Action)delegate
                {
                    block = AppendUpgradeProgramLog(data, brush);
                });
            }

            return block;
        }

        private void RemoveLastBlockAppendLog()
        {
            this.Dispatcher.Invoke((Action)delegate
            {
                this.rtxtUpgradeProgramLog.Document.Blocks.Remove(this.rtxtUpgradeProgramLog.Document.Blocks.LastBlock);
            });
        }

        #endregion

        #region PLC追加测试信息
        private Block AppendPLCTestData(string data, MyBrushes statusBrush)
        {
            Block block = null;

            if (this.Dispatcher.Thread == System.Threading.Thread.CurrentThread)
            {
                block = GetPLCBlock(data, statusBrush);

                this.rtxtPLCTestData.Document.Blocks.Add(block);
            }
            else
            {
                this.Dispatcher.Invoke((Action)delegate
                {
                    block = AppendPLCTestData(data, statusBrush);
                });
            }

            return block;
        }

        private Block GetPLCBlock(string data, MyBrushes statusBrush)
        {
            Inline inline = new Run(data);

            inline.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(statusBrush.ToBrushString()));

            return new Paragraph(inline) { LineHeight = 1.0 };
        }

        private void rtxtPLCTestData_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.rtxtPLCTestData.ScrollToEnd();
        }
        #endregion

    }
}
